在东部和格林威治标准时间之间错误地转换

时间:2014-03-25 14:35:51

标签: python pytz

我在将以下时间从东部转换为UTC / GMT时遇到了一个奇怪的问题。有人可以建议吗?

>>> import datetime
>>> import pytz
>>> 
>>> ept_time = datetime.datetime(2014,03,21,7)  # March 21st at 7am
>>> ept_time = ept_time.replace(tzinfo=pytz.timezone('US/Eastern'))
>>> print ept_time
2014-03-21 07:00:00-05:00
>>> 
>>> gmt_time = pytz.utc.normalize(ept_time)
>>> print gmt_time
2014-03-21 12:00:00+00:00
>>> 

然而,根据Wolfram Alpha,结果应该是上午11点,而不是12点。

1 个答案:

答案 0 :(得分:4)

>>> gmt = pytz.timezone('GMT')
>>> eastern = pytz.timezone('US/Eastern')
>>> d = datetime.datetime(2014,03,21,7)
>>> dateeastern = eastern.localize(d)
>>> dateeastern
datetime.datetime(2014, 3, 21, 7, 0, tzinfo=<DstTzInfo 'US/Eastern' EDT-1 day, 20:00:00 DST>)
>>> dategmt = dateeastern.astimezone(gmt)
>>> dategmt
datetime.datetime(2014, 3, 21, 11, 0, tzinfo=<StaticTzInfo 'GMT'>)

将GMT替换为UTC:

>>> eastern = pytz.timezone('US/Eastern')
>>> d = datetime.datetime(2014,03,21,7)
>>> dateeastern = eastern.localize(d)
>>> dateeastern
datetime.datetime(2014, 3, 21, 7, 0, tzinfo=<DstTzInfo 'US/Eastern' EDT-1 day, 20:00:00 DST>)
>>> dateutc = dateeastern.astimezone(pytz.utc)
>>> dateutc
datetime.datetime(2014, 3, 21, 11, 0, tzinfo=<UTC>)

参考:How to convert GMT time to EST time using python