转换时区+;TwitterAPI中的Python格式

转换时区+;TwitterAPI中的Python格式,python,twitter,timezone,Python,Twitter,Timezone,在Python中,通过TwitterSearch,我能够以UTC时间获取tweet的时间戳,格式如下: Thu Mar 19 12:37:15 +0000 2015 但是,我希望在EST时区(UTC-4)中以以下格式自动获取: 2015-03-19 08:37:15 这是我的代码示例。自动转换时,我应该更改哪些内容 for tweet in ts.search_tweets_iterable(tso): lat = None

在Python中,通过TwitterSearch,我能够以UTC时间获取tweet的时间戳,格式如下:

Thu Mar 19 12:37:15 +0000 2015
但是,我希望在EST时区(UTC-4)中以以下格式自动获取:

2015-03-19 08:37:15
这是我的代码示例。自动转换时,我应该更改哪些内容

            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()
提前谢谢你


Florent

从twitter发送的日期中删除+0000,然后执行以下操作:

from datetime import datetime
import pytz

local = 'Europe/London' #or the local from where twitter date is coming from
dt = datetime.strptime("Thu Mar 19 12:37:15 2015", "%a %b %d %H:%M:%S %Y")
dt = pytz.timezone(local).localize(dt)
est_dt = dt.astimezone(pytz.timezone('EST'))

print est_dt.strftime("%Y-%m-%d %H:%M:%S")
输出:

2015-03-19 07:37:15
或者,您可以执行以下操作(在这种情况下,您不需要删除+0000时区信息):

输出

2015-03-19 07:37:15

顺便说一下,EST是UTC-4或UTC-5?

从twitter发送的日期中删除+0000,然后执行以下操作:

from datetime import datetime
import pytz

local = 'Europe/London' #or the local from where twitter date is coming from
dt = datetime.strptime("Thu Mar 19 12:37:15 2015", "%a %b %d %H:%M:%S %Y")
dt = pytz.timezone(local).localize(dt)
est_dt = dt.astimezone(pytz.timezone('EST'))

print est_dt.strftime("%Y-%m-%d %H:%M:%S")
输出:

2015-03-19 07:37:15
或者,您可以执行以下操作(在这种情况下,您不需要删除+0000时区信息):

输出

2015-03-19 07:37:15

顺便说一下,EST是UTC-4或UTC-5?

如果EST是您的本地时区,则您可以仅使用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输入时区

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

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'

您可以将其放在函数中:

#!/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..

如果EST是您的本地时区,则您可以仅使用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输入时区

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

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'

您可以将其放在函数中:

#!/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..

如果输入是UTC格式,则此处使用
'Europe/London'
是错误的(后者有DST)。谢谢!我尝试了另一种解决方案,但这个似乎也很有趣。注意:
%b
取决于语言环境。如果脚本使用非英语语言环境,则可能无法解析时间字符串。如果输入为UTC,则此处使用
'Europe/London'
是错误的(后者具有DST)。谢谢!我尝试了另一种解决方案,但这个似乎也很有趣。注意:
%b
取决于语言环境。如果脚本使用非英语区域设置,则可能无法解析时间字符串。谢谢!请允许我问一个新手问题:我不确定应该把dt=datetime.fromtimstamp(timestamp,pytz.timezone('US/Eastern'))s=dt.strftime('%Y-%m-%d%H:%m:%s')放在我的代码中。@Flo
timestamp
的计算方法与答案中的第一个代码示例完全相同。哦,我明白了。但是我不能通过修改created_at=tweet['created_at']?@Flo什么是
repr(created_at)
,直接转换代码吗?从一个时区到另一个时区的任何正确转换都将使用UTC时间(POSIX时间戳)——可能是隐式的。您可以将代码放入函数中(它接受一种时间格式,并以另一种格式和另一个时区返回相同的时间),以创建一种“直接转换”的错觉。非常感谢,我已经编写了以下代码,它工作得非常好:user_creation=mktime_tz(parsedate_tz(tweet['user']['created_at'])timetext\u user=str(datetime.fromtimstamp(user\u creation))timestamp=mktime\u tz(parsedate\u tz(tweet['created\u at']))timetext=str(datetime.fromtimstamp(timestamp))谢谢!请允许我问一个新手问题:我不确定应该把dt=datetime.fromtimstamp(timestamp,pytz.timezone('US/Eastern'))s=dt.strftime('%Y-%m-%d%H:%m:%s')放在我的代码中。@Flo
timestamp
的计算方法与答案中的第一个代码示例完全相同。哦,我明白了。但是我不能通过修改created_at=tweet['created_at']?@Flo什么是
repr(created_at)
,直接转换代码吗?从一个时区到另一个时区的任何正确转换都将使用UTC时间(POSIX时间戳)——可能是隐式的。您可以将代码放入函数中(它接受一种时间格式,并以另一种格式和另一个时区返回相同的时间),以创建一种“直接转换”的错觉。非常感谢,我已经编写了以下代码,它工作得非常好:user_creation=mktime_tz(parsedate_tz(tweet['user']['created_at'])timetext\u user=str(datetime.fromtimstamp(user\u creation))timestamp=mktime\u tz(parsedate\u tz(tweet['created\u at']))timetext=str(datetime.fromtimstamp(timestamp))