I'm reading the not so complete pytz documentation and I'm stuck on understand one part of it.
Converting between timezones also needs special attention. This also needs to use the normalize method to ensure the conversion is correct.
>>> utc_dt = utc.localize(datetime.utcfromtimestamp(1143408899)) >>> utc_dt.strftime(fmt) '2006-03-26 21:34:59 UTC+0000' >>> au_tz = timezone('Australia/Sydney') >>> au_dt = au_tz.normalize(utc_dt.astimezone(au_tz)) >>> au_dt.strftime(fmt) '2006-03-27 08:34:59 EST+1100' >>> utc_dt2 = utc.normalize(au_dt.astimezone(utc)) >>> utc_dt2.strftime(fmt) '2006-03-26 21:34:59 UTC+0000'
I tried this very example without using normalize
and it turned out just the same. In my opinion this example doesn't really explain why we have to use normalize
when converting between datetime
objects in different timezones.
Would someone please give me an example (like the one above) where the result differs when not using normalize
.
Thanks
The pytz module allows for date-time conversion and timezone calculations so that your Python applications can keep track of dates and times, while staying accurate to the timezone of a particular location.
Note: pytz is now obsolete (since two weeks), so with Python 3.9 you can uses directly standard libraries.
From the pytz documentation:
In addition, if you perform date arithmetic on local times that cross DST boundaries, the results may be in an incorrect timezone (ie. subtract 1 minute from 2002-10-27 1:00 EST and you get 2002-10-27 0:59 EST instead of the correct 2002-10-27 1:59 EDT). A normalize() method is provided to correct this. Unfortunately these issues cannot be resolved without modifying the Python datetime implementation.
The docs say that normalize is used as a workaround for DST issues:
In addition, if you perform date arithmetic on local times that cross DST boundaries, the results may be in an incorrect timezone (ie. subtract 1 minute from 2002-10-27 1:00 EST and you get 2002-10-27 0:59 EST instead of the correct 2002-10-27 1:59 EDT). A normalize() method is provided to correct this.
So it's used to correct some edge cases involving DST. If you're not using DST timezones (e.g. UTC) then it's not necessary to use normalize.
If you don't use it your conversion could potentially be one hour off under certain circumstances.
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