Problems with Naive Datetimes in TZ-aware Django

2016-03-30 | #django, #solution, #webdev

I came about this problem recently during th switch to daylight savings time here in Germany, when a garbage collecting task on my database failed for one hour continuously after the switch, while it normally worked flawlessly. For exactly one hour I received an avalanche of exception mails, all stating the same exception about a "non existent time". What happened here?

What I did, and what was also my misstake, was to create a new timestamp with datetime.datetime.now() and used a timedelta to subtract an hour from it and then tried to query my database for fitting entries. What happended was, that I tried to search for entries whose creation timestamp was smaller than, for example, the night of the switch at 2:01am. Well, tough luck, there is nothing between 2 and 3am on the day of the switch. So my timezone aware Django-project rightfully cried "Foul play, mister!".

So how do I deal with this without tearing my hair?

You have to make sure to always use timezone aware date and datetime object, as long as your Django project is configured as being timezone aware in its settings (as it is by default).

The easiest way to circumvent such calculation fuckups as mine is to get all your timestamps from Django's django.utils.timezone-package.

To get a secure now(), for example, do this:

from django.utils import timezone

now = timezone.now()