It’s about time! - Aymeric Augustin

Tags: django, djangocon

iso8601 is a standard for representing time. The current date, offset to universal time, universal time and timezone.

In python you have to use pytz to get proper timezone support for python’s datetime. With it you can give the right timezone to datetime and render the time easily in a local timezone.

A big problem is that you have timezone-aware datetimes and naive datetimes (so, without timezone info): you cannot compare them! Naive datetime objects are easier to work with, but they ignore relevant aspects of reality. Like daylight savings time (DST).

Especially the twice-a-year time jump for DST can be hard to handle. In Europe you even switch timezones: CEST to CET (central european (summer) time).

You could get the idea to just use naive regular datetimes in UTC (~GMT). But you will have to deal with local times anyway. Which time do you display? Do you talk to a webservice that gives back local time? Etc.

Just like Joel Spolsky said there ain’t no such thing as plain text (when explaining unicode), Aymeric says “there ain’t no such thing as a naive datetime”.

Also watch out when comparing dates. time_in_newyork == time_in_losangeles might be fully True with datetime-aware times. But if you compare the dates, time_in_newyork.date() == time_in_losangeles.date() might be False because it is midnight halfway the US. Dates are always naive.

Django now (1.4+) has better support for timezones. You do have to set``USE_TZ = True``. Django 1.4 uses aware datetimes in UTC internally. But it stores naive datetimes in UTC in the database (except postgresql). In forms and templates, it converts to local time. When django needs to use a default timezone, because it doesn’t know which one to use, it uses settings.TIME_ZONE. In templates and forms it uses the end user’s time zone.

Have a look at from django.utils import timezone. Here are the docs. timezone.now() gives you the current time, for instance.

Some key things he learned from working on django’s timezone support:

  • A datetime is a point in time. A date is a calendering concept.

  • Use aware datetimes in UTC and convert to local time for humans.

  • Learn how to use pytz properly, especially localize() and normalize().

“Time isn’t as simple as it seems.”

Photo & Video Sharing by SmugMug
 
vanrees.org logo

About me

My name is Reinout van Rees and I work a lot with Python (programming language) and Django (website framework). I live in The Netherlands and I'm happily married to Annie van Rees-Kooiman.

Weblog feeds

Most of my website content is in my weblog. You can keep up to date by subscribing to the automatic feeds (for instance with Google reader):