dateutil timezone question

Skip Montanaro skip.montanaro at
Fri Dec 23 15:09:21 EST 2016

> I did mess around with pytz a bit but I was getting a lot of
> exceptions - something related to the TZ already being set or
> something like that. I don't recall exactly, and I can't scroll back
> far enough to find it.

Yes, if the tzinfo attribute has already been set, you will get errors from localize(). Once a datetime object has a valid timezone, you can compare it with other tz-aware datetime objects. They need not be in the same timezone.

For visual purposes (for instance, when writing to logfiles), it can be handy to display all timestamps in the same timezone. For that, you can use the normalize() method of timezone objects. Here's a simple example:

>>> import datetime, pytz

Here's a datetime in UTC, but still naive (no tzinfo attribute).

>>> utcnow = datetime.datetime.utcnow()
>>> print utcnow.tzinfo

Localize to UTC et voila!

>>> utcnow = pytz.utc.localize(utcnow)
>>> print utcnow.tzinfo
>>> chicago = pytz.timezone("America/Chicago")
>>> print utcnow
2016-12-23 20:04:51.295127+00:00
>>> print chicago.normalize(utcnow)
2016-12-23 14:04:51.295127-06:00

Different timezones, but the same time.

>>> print utcnow - chicago.normalize(utcnow)


More information about the Python-list mailing list