【发布时间】:2014-10-12 05:42:55
【问题描述】:
我从数据库中得到一个类似2014/08/19 03:38:46 GMT-4 的日期。
如何在 Python 中将其转换为 UTC 格式的日期?
PS:我使用 Python 2.6.6
【问题讨论】:
标签: python utc python-2.6 gmt pytz
我从数据库中得到一个类似2014/08/19 03:38:46 GMT-4 的日期。
如何在 Python 中将其转换为 UTC 格式的日期?
PS:我使用 Python 2.6.6
【问题讨论】:
标签: python utc python-2.6 gmt pytz
拥有一个非天真的日期时间对象,您应该只调用具有所需时区的astimezone 方法
>>> import pytz
>>> from dateutil import parser
# dateutil.parser get a datetime object from string, we ensure that is a non-naive datetime
>>> parser.parse('2014/08/19 03:38:46 GMT-4')
datetime.datetime(2014, 8, 19, 3, 38, 46, tzinfo=tzoffset(None, 14400))
>>> dt = parser.parse('2014/08/19 03:38:46 GMT-4')
>>> dt.astimezone (pytz.utc)
datetime.datetime(2014, 8, 18, 23, 38, 46, tzinfo=<UTC>)
你的评论是对的,UTC时间应该落后,所以虽然我认为另一种解决方案,这个呢
>>> dt = parser.parse('2014/08/19 03:38:46 GMT-4')
>>> dt.replace(tzinfo=pytz.utc) + dt.tzinfo._offset
datetime.datetime(2014, 8, 19, 7, 38, 46, tzinfo=<UTC>)
【讨论】:
dt.utcoffset() 而不是dt.tzinfo._offset
GMT-4 不明确:是在 America/New_Your(-0400 utc offset)还是在欧洲/莫斯科(+0400)?
$ TZ=GMT-4 date +%Z%z
GMT+0400
$ TZ=UTC-4 date +%Z%z
UTC+0400
$ TZ=America/New_York date +%Z%z
EDT-0400
$ TZ=Europe/Moscow date +%Z%z
MSK+0400
Your comment suggests 表示您需要反转 utc 偏移量的符号。
Python 2.6 在 stdlib 中没有固定偏移时区。你可以使用the example implementation from the datetime docs:
from datetime import tzinfo, timedelta, datetime
ZERO = timedelta(0)
class FixedOffset(tzinfo):
"""Fixed UTC offset: `local = utc + offset`."""
def __init__(self, offset, name):
self.__offset = timedelta(hours=offset)
self.__name = name
def utcoffset(self, dt):
return self.__offset
def tzname(self, dt):
return self.__name
def dst(self, dt):
return ZERO
utc = FixedOffset(0, "UTC")
然后解析时间字符串,可以使用strptime():
dt = datetime.strptime("2014/08/19 03:38:46 GMT-4", "%Y/%m/%d %H:%M:%S GMT-4")
aware = dt.replace(tzinfo=FixedOffset(-4, "GMT-4"))
print(aware) # -> 2014-08-19 03:38:46-04:00
print(aware.astimezone(utc)) # -> 2014-08-19 07:38:46+00:00
【讨论】: