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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With