从 Twitter API 在 Python 中转换时区 + 格式 [英] Convert Time Zone + format in Python from Twitter API

查看:38
本文介绍了从 Twitter API 在 Python 中转换时区 + 格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Python 中,使用 TwitterSearch,我能够以 UTC 时间获取推文的时间戳,格式如下:

In Python, with TwitterSearch, I'm able to get the timestamp of the tweet in UTC time, in the following format :

Thu Mar 19 12:37:15 +0000 2015

但是,我想以这种格式在 EST 时区 (UTC - 4) 中自动获取它:

However, I would like to obtain it automatically in the EST timezone (UTC - 4), in this format :

2015-03-19 08:37:15

这是我的代码示例.我应该在其中更改哪些内容以进行自动转换?

Here is a sample of my code. What should I change in it for an automatic conversion?

            for tweet in ts.search_tweets_iterable(tso):
            lat = None
            long = None
            user = tweet['user']['screen_name']
            user_creation = tweet['user']['created_at']
            created_at = tweet['created_at'] # UTC time when Tweet was created.
            favorite = tweet['favorite_count']
            retweet = tweet ['retweet_count']
            id_status = tweet['id']
            in_reply_to = tweet['in_reply_to_screen_name']
            followers = tweet['user']['followers_count'] # nombre d'abonnés
            statuses_count = tweet['user']['statuses_count'] # nombre d'abonnés
            location = tweet['user']['location'] # résidence du twittos
            tweet_text = tweet['text'].strip() # deux lignes enlèvent espaces inutiles
            tweet_text = ''.join(tweet_text.splitlines())
            print i,created_at,user_creation,user, tweet_text
            if tweet['geo'] and tweet['geo']['coordinates'][0]: 
                lat, long = tweet['geo']['coordinates'][:2]
                print u'@%s: %s' % (user, tweet_text), lat, long
            else:
                print u'@%s: %s' % (user, tweet_text)
            print favorite,retweet,id_status,in_reply_to,followers,statuses_count,location

            writer.writerow([user.encode('utf8'), user_creation.encode('utf8'), created_at.encode('utf8'), 
                             tweet_text.encode('utf8'), favorite, retweet, id_status, in_reply_to, followers, statuses_count, location.encode('utf8'), lat, long])
            i += 1
            if i > max:
                return()

先谢谢你!

佛罗伦萨

推荐答案

如果 EST 是您的本地时区,那么您可以只使用 stdlib:

If EST is your local timezone then you could do it using only stdlib:

#!/usr/bin/env python
from datetime import datetime
from email.utils import parsedate_tz, mktime_tz

timestamp = mktime_tz(parsedate_tz('Thu Mar 19 12:37:15 +0000 2015'))
s = str(datetime.fromtimestamp(timestamp))
# -> '2015-03-19 08:37:15'

它也支持非 UTC 输入时区.

It supports non-UTC input timezones too.

或者您可以明确指定目标时区:

Or you could specify the destination timezone explicitly:

import pytz # $ pip install pytz

dt = datetime.fromtimestamp(timestamp, pytz.timezone('US/Eastern'))
s = dt.strftime('%Y-%m-%d %H:%M:%S')
# -> '2015-03-19 08:37:15'

<小时>

你可以把它放在一个函数中:


You could put it in a function:

#!/usr/bin/env python
from datetime import datetime
from email.utils import parsedate_tz, mktime_tz

def to_local_time(tweet_time_string):
    """Convert rfc 5322 -like time string into a local time
       string in rfc 3339 -like format.

    """
    timestamp = mktime_tz(parsedate_tz(tweet_time_string))
    return datetime.fromtimestamp(timestamp).strftime('%Y-%m-%d %H:%M:%S')

time_string = to_local_time('Thu Mar 19 12:37:15 +0000 2015')
# use time_string here..

这篇关于从 Twitter API 在 Python 中转换时区 + 格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆