简体   繁体   中英

What is wrong with my conversion from local time to UTC

According to timeanddate.com, currently Chicago is 5 hours behind UTC. However, my Python app thinks differently:

import datetime
import pytz

    local_tz = pytz.timezone('America/Chicago')
    local_time = datetime.datetime(2015, 8, 6, 0, 0, tzinfo=local_tz)
    utc_time = local_time.astimezone(pytz.utc)
    print(local_time)
    print(utc_time)

2015-08-06 00:00:00-05:51
2015-08-06 05:51:00+00:00

I am getting the same results with both 'America/Chicago' and 'US/Central'. Why is the offset -05:51 instead of -05:00?

pytz timezone objects need to be initialized with a specific time before they're used, and creating a datetime with a tzinfo= parameter does not allow for that. You have to use the localize method of the pytz object to add the timezone to the datetime .

>>> local_tz = pytz.timezone('America/Chicago')
>>> local_time = local_tz.localize(datetime.datetime(2015, 8, 6, 0, 0))
>>> print local_time
2015-08-06 00:00:00-05:00
>>> utc_time = local_time.astimezone(pytz.utc)
>>> print utc_time
2015-08-06 05:00:00+00:00

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