Login

astimezone template tag

Author:
whardier
Posted:
March 9, 2011
Language:
Python
Version:
1.2
Score:
2 (after 2 ratings)

should probably be migrated to an inclusion tag to allow a source timezone that isn't the site specific TIME_ZONE.

This code assumes that your database stores dates according to the django.conf.settings.TIME_ZONE variable.

Yes.. this assumes that dates are stored in the database according to system time. On my systems the system time of a server is always UTC therefore avoiding problems with datetime (no tz info) columns in backend databases having no timezone information and stored according to the database or system timezone information. I find it a good practice to always use UTC for any stored information and always retrieve information as UTC and localize the date during display.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
from django import template
from django.conf import settings

import pytz

register = template.Library()

@register.filter
def astimezone(date, destination=None):

    if not destination:
        destination = settings.TIME_ZONE

    if date.tzinfo:
        return date.astimezone(pytz.timezone(destination))
    else:
        return pytz.timezone(settings.TIME_ZONE).localize(date).astimezone(pytz.timezone(destination))

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 11 months, 1 week ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months, 2 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 6 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 7 months ago
  5. Help text hyperlinks by sa2812 1 year, 7 months ago

Comments

Please login first before commenting.