The strange beast of PyTZ and datetime

Posted on November 11, 2014

The crux of this post is, make sure to never use datetime.replace(tzinfo=...) when working with PyTZ, use tz.localize(...) instead, otherwise you’ll end up with some very strange times.

The PyTZ docs do mention this helper method as a way to fix incorrect conversion across timezones, but out of the box PyTZ timezones seem odd. Consider this simple code that takes both the native datetime.replace approach, and the localize approach:

The output is:

Off the bat, notice that the representation of the PyTZ timezone is strange: “LMT+10:12:00”. For a start, what is LMT? And why is there an extra 12 minutes in the offset? The correct format would be something like: AEST+10:00:00. i.e., the timezone abbreviation is AEST, and the offset is 10 hours.

When you apply this in a naive way you end up with the incorrect offset, and when you take this across to UTC the answer is wrong. But, when you apply the timezone using localize method the correct offset.

Certainly something to be aware of.