我从数据库中得到2014/08/19 03:38:46 GMT-4
之类的日期。
如何在Python中将其转换为UTC格式的日期?
PS:我使用Python 2.6.6
答案 0 :(得分:4)
拥有非天真的日期时间对象,您只应使用所需的时区调用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>)
你的评论是正确的,时间应该落后,所以当我想到另一个解决方案时,这个怎么样
>>> 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>)
答案 1 :(得分:1)
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