How (not) to screw up timezone processing in Python

By | September 26, 2012

If you use pytz without reading the documentation, you might think you can do this:

This is an easy way to utterly screw up your timezones.

Never pass a tzinfo into the datetime constructor. Here’s why:

That’s simply the wrong time. 1:15 Chilean time should be 21:15 Pacific the previous day, not 22:58.

For whatever reason, the wrong tzinfo is attached to the object. Compare:

The correct way is to use pytz.localize():

The pytz documentation does not indicate if creates the correct timezone, so I tested it:

The assertion never failed, so it is safe to use"[timezonename]")) to generate the current date in a specific timezone.

In general, you should store dates in UTC format and convert them to the user’s timezone at the latest possible time. Try to never store naive datetimes. if you need the current time in UTC, use

because utcnow() returns a naive datetime. Localizing it to UTC adds the correct timezone to it.

is the correct way to construct a datetime in the UTC timezone. Technically, you CAN pass tzinfo to the datetime constructor if tzinfo is UTC. This is because UTC does not have daylight savings time. However, for consistency, do not do this; do not ever pass tzinfo into a datetime constructor.

Converting to or from UTC is simple, using astimezone:

One thought on “How (not) to screw up timezone processing in Python

Leave a Reply

Your email address will not be published. Required fields are marked *