Python: How to convert a timezone aware timestamp to UTC without knowing if DST is in effect

user1152532 picture user1152532 · Oct 22, 2013 · Viewed 18.5k times · Source

I am trying to convert a naive timestamp that is always in Pacific time to UTC time. In the code below, I'm able to specify that this timestamp I have is in Pacific time, but it doesn't seem to know that it should be an offset of -7 hours from UTC because it's only 10/21 and DST has not yet ended.

The script:

import pytz
import datetime
naive_date = datetime.datetime.strptime("2013-10-21 08:44:08", "%Y-%m-%d %H:%M:%S")
localtz = pytz.timezone('America/Los_Angeles')
date_aware_la = naive_date.replace(tzinfo=localtz)
print date_aware_la

Outputs:

    2013-10-21 08:44:08-08:00

It should have an offset of -07:00 until DST ends on Nov. 3rd. How can I get my timezone aware date to have the correct offset when DST is and is not in effect? Is pytz smart enough to know that DST will be in effect on Nov 3rd?

Overall goal: I'm just trying to convert the timestamp to UTC knowing that I will be getting a timestamp in pacific time without any indication whether or not DST is in effect. I'm not generating this date from python itself, so I'm not able to just use utc_now().

Answer

Matt Johnson-Pint picture Matt Johnson-Pint · Oct 22, 2013

Use the localize method:

import pytz
import datetime
naive_date = datetime.datetime.strptime("2013-10-21 08:44:08", "%Y-%m-%d %H:%M:%S")
localtz = pytz.timezone('America/Los_Angeles')
date_aware_la = localtz.localize(naive_date)
print(date_aware_la)   # 2013-10-21 08:44:08-07:00

This is covered in the "Example & Usage" section of the pytz documentation.

And then continuing to UTC:

utc_date = date_aware_la.astimezone(pytz.utc)
print(utc_date)