Skip to content Skip to sidebar Skip to footer

Python: How To Convert A Timezone Aware Timestamp To Utc Without Knowing If Dst Is In Effect

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 do

Solution 1:

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)

Post a Comment for "Python: How To Convert A Timezone Aware Timestamp To Utc Without Knowing If Dst Is In Effect"