Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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

like image 416
user1152532 Avatar asked Oct 22 '13 20:10

user1152532


People also ask

How do I change timezone to UTC in Python?

Use the pytz module, which comes with a full list of time zones + UTC. Figure out what the local timezone is, construct a timezone object from it, and manipulate and attach it to the naive datetime. Finally, use datetime. astimezone() method to convert the datetime to UTC.

How do you convert time stamp to UTC?

You can use the datetime module to convert a datetime to a UTC timestamp in Python. If you already have the datetime object in UTC, you can the timestamp() to get a UTC timestamp. This function returns the time since epoch for that datetime object.

How do you generate UTC time in Python?

Getting the UTC timestampUse the datetime. datetime. now() to get the current date and time. Then use tzinfo class to convert our datetime to UTC.

Is Python datetime timezone aware?

Timezone-aware objects are Python DateTime or time objects that include timezone information. An aware object represents a specific moment in time that is not open to interpretation.


1 Answers

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)
like image 197
Matt Johnson-Pint Avatar answered Oct 18 '22 15:10

Matt Johnson-Pint