Nick Nick - 2 months ago 13
Python Question

Python datetime difference between .localize and tzinfo

Why do these two lines produce different results?

>>> import pytz
>>> from datetime ipmort datetime

>>> local_tz = pytz.timezone("America/Los_Angeles")

>>> d1 = local_tz.localize(datetime(2015, 8, 1, 0, 0, 0, 0)) # line 1
>>> d2 = datetime(2015, 8, 1, 0, 0, 0, 0, local_tz) # line 2
>>> d1 == d2
False


What's the reason for the difference, and which should I use to localize a datetime?

Answer

When you create d2=datetime(2015, 8, 1, 0, 0, 0, 0, local_tz) in this way. It does not handle daylight savings time correctly. But, local_tz.localize() does.

d1 is

datetime.datetime(2015, 8, 1, 0, 0, 
                  tzinfo=<DstTzInfo 'America/Los_Angeles' PDT-1 day, 17:00:00 DST>)

d2 is

datetime.datetime(2015, 8, 1, 0, 0, 
                  tzinfo=<DstTzInfo 'America/Los_Angeles' PST-1 day, 16:00:00 STD>)

You can see that they are not representing the same time.

d2 way it's fine if you are gonna work with UTC. Because UTC does not have daylight savings time transitions to deal with.

So, the correct way to handle timezone, it's using local_tz.localize()

Comments