python将时间转换为utc时间?

时间:2014-11-16 15:04:58

标签: python datetime

我有一个date_object.time(),它是Asia/Taipei时间

date_object.time() = '10:00:00'

我得到datetime.datetime.now时区Asia/Taipei

current = datetime.datetime.now(pytz.utc)
taipeitime = current.replace(tzinfo=pytz.utc).astimezone(pytz.timezone('Asia/Taipei'))

然后我将date_object.time()taipeitime

组合在一起
combine = datetime.datetime.combine(taipeitime, date_object.time()) #Asia/Taipei time

我必须将combine转换为UTC时间 但我得到错误:

print combine.astimezone(pytz.utc)
ValueError: astimezone() cannot be applied to a naive datetime

请教我如何转换这个?谢谢

1 个答案:

答案 0 :(得分:0)

datetime的.time()方法丢失了时区信息,使用.timetz()代替:

>> combine = datetime.datetime.combine(taipeitime, taipeitime.timetz())
>> combine.astimezone(pytz.utc)

datetime.datetime(2014, 11, 16, 15, 13, 46, 948201, tzinfo=<UTC>)

VS

>> combine = datetime.datetime.combine(taipeitime, taipeitime.time())
>> combine.astimezone(pytz.utc)

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: astimezone() cannot be applied to a naive datetime

请参阅https://docs.python.org/2/library/datetime.html#datetime.datetime.timetz

您还可以将时区替换为时间对象,例如

combine = datetime.datetime.combine(taipeitime,
                   taipeitime.time().replace(tzinfo=pytz.timezone('Asia/Taipei')))

会为您提供时区感知的组合时间。见https://docs.python.org/2/library/datetime.html#datetime.time.replace