Managing timezone aware datetime objects

Dealing with date and time can be quite tricky. Specially if we need to convert local times from different timezones. Lets see what standard Python datetime module does:

[gist]https://gist.github.com/805087[/gist]

The generated timestamp is in ISO8601 format, well, not really, microsecds should be removed, but that’s not the biggest problem. The problem is that the offset from UTC is not added. If a timestamp is generated in a local form, the offset to UTC must be provided, lets see an example:

2011-02-01T00:56:23+01:00

That means that the local time is 00:56:23, which is +01:00 hours ahead UTC. Regular Python datetime objects are not timezone aware. Getting proper timezone information is a tough matter, but fortunately the dateutil module will help. Lets see it in action:

[gist]https://gist.github.com/805107[/gist]

Hey! Now the timestamp is generated correctly! (I set the microsecond to 0 so that its fully ISO 8601 compliant). We can also use the dateutil module to parse a timestamp and generate a timezone-aware object out of it:

[gist]https://gist.github.com/805117[/gist]

One last note: if you need to perform operations such as calculating the difference between two datetime objects, they both need to be timezone aware, otherwise bad things happen:

[gist]https://gist.github.com/805121[/gist]

:wq

Leave a Reply

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