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?
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
d2 is
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()