AlexC
AlexC

Reputation: 3914

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?

Upvotes: 4

Views: 525

Answers (1)

Mark Ransom
Mark Ransom

Reputation: 308528

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

Upvotes: 4

Related Questions