$30 off During Our Annual Pro Sale. View Details »

Timezone support in Django

Timezone support in Django

On Python datetime and timezone support in Django. Not a pretty sight.

Tzu-ping Chung

January 22, 2014
Tweet

More Decks by Tzu-ping Chung

Other Decks in Programming

Transcript

  1. Timezone in Websites • Totally broken in all possible ways

    • Two negatives make a positive! • But if you (by chance) get some of them right…
  2. Databases • All databases do not support timezones • PostgreSQL:

    yes • SQLite: no • MySQL: sometimes • Django stores everything in UTC
  3. Naïve vs Aware >>> import datetime! >>> now = datetime.datetime.now()!

    >>> print now! 2014-01-21 19:09:14.960786! >>> print now.replace(tzinfo=taipei)! 2014-01-21 19:09:14.960786+08:00
  4. Naïve vs Aware >>> import datetime! >>> now = datetime.datetime.now()!

    >>> print now! 2014-01-21 19:09:14.960786! >>> print now.replace(tzinfo=taipei)! 2014-01-21 19:09:14.960786+08:00 naïve aware
  5. naïve /nai-eev/ 1. Lacking worldly experience, wisdom, or judgement; unsophisticated.

    Surely you're not naïve enough to believe adverts! … http://en.wiktionary.org/wiki/naive
  6. pytz • The Olson Timezone Database • pip install pytz

    • taipei = pytz.timezone(‘Asia/Taipei') • Django depends on this for timezone support http://pytz.sourceforge.net
  7. USE_TZ • USE_TZ = False • Naïve objects with your

    default timezone • USE_TZ = True • Aware objects (Naïve ones generate warnings) • Django makes a date/time aware automatically when it’s retrieved from database
  8. >>> from django.utils.timezone import *! >>> print now()! 2014-01-21 11:09:14.960786+00:00!

    >>> from django.conf import settings! >>> print settings.USE_TZ! True django.utils.timezone
  9. HTTP • HTTP header doesn’t have a “Accept-Timezone” field •

    You need to manually set a request’s timezone if you need timezone support
  10. from django.utils.timezone import *! from pytz import timezone! ! taipei

    = timezone('Asia/Taipei')! activate(taipei)! ! print get_current_timezone_name()! # Asia/Tapei! ! with override(utc):! print get_current_timezone_name()! # UTC! ! deactivete()
  11. {# "value" is a date/time object #}! ! {% load

    tz %}! ! {# Neither of these respect USE_TZ #}! {% localtime on %}! {{ value }}! {% endlocaltime %}! ! {% localtime off %}! {{ value }}! {% endlocaltime %}
  12. {% load tz %}! ! {% timezone "Europe/Paris" %}! Paris

    time: {{ value }}! {% endtimezone %}! ! {% get_current_timezone as timezone %}! ! {{ value|localtime }}! ! {{ value|utc }}! ! {{ value|timezone:"Europe/Paris" }}
  13. DST • No universal standard • Varies every year •

    Some nations only partly use it (e.g. Australia) • pytz helps (but you still need to be cautious)