简体   繁体   中英

python convert time to utc time?

I have a date_object.time() ,it's Asia/Taipei time

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

And I get the datetime.datetime.now with timezone Asia/Taipei

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

And then I combine the date_object.time() and taipeitime

combine = datetime.datetime.combine(taipeitime, date_object.time()) #Asia/Taipei time

And I have to convert the combine to UTC time But I get error:

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

Please teach me how to convert this? Thank you

The .time() method for datetime looses the timezone info, use .timetz() instead eg:

>> 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

see https://docs.python.org/2/library/datetime.html#datetime.datetime.timetz .

Also you can replace the timezone into the time object, eg

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

will get you a timezone aware combine time. See https://docs.python.org/2/library/datetime.html#datetime.time.replace

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM