Timezone management in Django

 

Timezone management in Django is not straightforward. This is a recap of what to be aware of when playing with them.

When using a MySQL or MongoDB database on Django, the datetime fields are stored without any information about the timezone. This is prone to errors and implies to be careful to always store datetime into the same timezone (UTC is highly recommended, but another is possible as long as the same one is always used).

In Django settings, there are two parameters to configure the Timezone problem: TIME_ZONE and USE_TZ.

TIME_ZONE configures the project timezone, which will be used as follow depending on USE_TZ:

  • When USE_TZ=False, Django will store all datetime in TIME_ZONE on the DB. For example, 2021-04-21T14:01:56.449815+02:00 will be stored as 2021-04-21T14:01:56.449815 on the DB.
  • When USE_TZ=True, Django will store all datetim in UTC on the DB. For example, 2021-04-21T14:01:56.449815+02:00 will be stored as 2021-04-21T12:01:56.449815 on the DB. With this option enabled, Django will also use TIME_ZONE to display datetimes in templates and to interpret datetimes entered in forms.

So it is strongly advised to use USE_TZ=True, and to always work with UTC datetimes into the code and timezone-related datetimes when interacting with end users (see this django doc. To change the timezone depending on the user, there are some solutions available.

  • For instance, for registered users, a field containing the timezone could be added in the User model, and a user profile page added so that each user could select its timezone. A middleware would then set the user’s timezone when requests are done.
  • Another example for visitors is to have a selector (like language but for timezone), and the store the choice in the user’s cookies. Again, a middleware would then be necessary.
  • Finally, there are libraries like django-visitor-information, which is a collection of middlewares that fill Request with information about the visitors (like country, city, timezone) based on it IP Address.

For more detailed considerations about the timezones in python, see https://julien.danjou.info/python-and-timezones/.