Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python datetime difference between .localize and tzinfo

Why do these two lines produce different results?

>>> import pytz
>>> from datetime import 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?

like image 273
Nick Avatar asked Sep 12 '16 23:09

Nick


1 Answers

When you create d2 = datetime(2015, 8, 1, 0, 0, 0, 0, local_tz), it does not handle daylight saving time (DST) correctly. local_tz.localize() does.

d1 is

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

d2 is

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

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

d2 way is fine if you are going to work with UTC. UTC does not have daylight saving time (DST) transitions to deal with.

The correct way to handle timezone is to use local_tz.localize() to support daylight saving time (DST)

More information and additional examples can be found here:
http://pytz.sourceforge.net/#localized-times-and-date-arithmetic

like image 175
levi Avatar answered Nov 15 '22 17:11

levi