07/17/2012

Django 1.4: Swatting Those Pesky DST Bugs

Twice a year most of us have to deal with springing forward then falling back when daylight savings time (DST) kicks in and out. Our web apps need to deal with it too, but on some platforms the transition introduces pesky bugs that are hard to replicate and kill.

With the latest release of Django 1.4, the twice-a-year change doesn't have to be a frustrating bug search. Support for time zones now allows web apps to be aware of their time zone and make adjustments appropriately (finally!). Here's what the release notes say about time zone implementation in 1.4:

  • The database now stores date and time in UTC
  • Support for internal time zone aware objects
  • Translations are made to display the proper time to the user

This welcome change though, introduces issues for some users that have legacy projects relying on naive (time zone agnostic) datetime objects. If you're using a PostgreSQL database then you're probably all set. Dates and times are already stored in a fashion that converts them to Coordinated Universal Time (UTC) which is the time standard used around the world. If you're using any other database however, you'll need to take some steps to ensure that your code functions properly once you turn on support for time zones.

The migration guide outlines three steps to bring code using naive datetime objects to full functionality:

  1. Add "USE_TZ = True" to your settings file (also install pytz, the Python World Time Zone Definitions)
  2. Refactor the code to make datatime objects aware (vs. naive)
  3. Use the warnings generated for naive datetime objects to create exceptions that allow you to traceback in the code where the objects are

To help in refactoring the code you can use django.utils.timezone. This set of functions helps create compatible code:

  • now()
  • is_aware()
  • is_naive()
  • make_aware()
  • make_naive()

If you haven't started migrating yet, take a few minutes to look at the 1.4 FAQ and migration guide on djangoproject.com. You'll be glad you did when you start falling back November 4th.