Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pytz: Why is normalize needed when converting between timezones?

Tags:

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

like image 932
Deniz Dogan Avatar asked Sep 14 '09 17:09

Deniz Dogan


People also ask

What does pytz timezone do?

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.

Is pytz obsolete?

Note: pytz is now obsolete (since two weeks), so with Python 3.9 you can uses directly standard libraries.


2 Answers

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.

like image 144
Wooble Avatar answered Sep 22 '22 17:09

Wooble


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.

like image 21
Steven Kryskalla Avatar answered Sep 20 '22 17:09

Steven Kryskalla