22

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().

user1152532
  • 697
  • 3
  • 7
  • 15

1 Answers1

26

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)
Matt Johnson-Pint
  • 230,703
  • 74
  • 448
  • 575
  • 4
    to assert that `naive_date` is unambiguous and exists, you could pass `is_dst=None` to `localize()`; otherwise the wrong time maybe selected silently. – jfs Mar 27 '14 at 08:08
  • The question was about timezone-_aware_ datetime. – Anthony Nov 30 '22 at 20:26
  • @Anthony - Not really. The title is confusing because it is asking about fixing an incorrectly made aware datetime, but really the problem and its solution are to create it correctly in the first place. We sometimes call this [the "XY problem"](https://meta.stackexchange.com/a/66378/201534). (The question title is about Y, but the question body indicates the problem is actually X.) – Matt Johnson-Pint Nov 30 '22 at 23:34
  • Wow! May be it is better to correct title accordingly? – Anthony Dec 01 '22 at 10:11