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:


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:


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:


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:


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:



Leave a Reply

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