filter dates to user profile's timezone

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
import pytz
from django.conf import settings
from django.core.exceptions import ObjectDoesNotExist

@register.filter()
def user_tz(value, user):
    """Expects a datetime as the value. Expects a User object as the arg.
    Looks up the 'timezone' value in the user's profile, and converts
    the given datetime in to one in the user's timezone.

    NOTE: This assumes that you have the 'pytz' module
    (pytz.sourceforge.net) and that the user profile has a field
    called 'timezone' that is a character string and that the timezone
    thus specified is a valid timezone supported by pytz.
    """
    tz = settings.TIME_ZONE
    if isinstance(user, User):
        try:
            tz = user.get_profile().timezone
        except ObjectDoesNotExist:
            pass
    try:
        result = value.astimezone(pytz.timezone(tz))
    except ValueError:
        # Hm.. the datetime was stored 'naieve' ie: without timezone info.
        # we assume the timezone in 'settings' for all naieve objects.
        #
        result = value.replace(tzinfo=pytz.timezone(settings.TIME_ZONE)).astimezone(pytz.timezone(tz))
    return result

More like this

  1. UTC DateTime field by ludo 5 years, 9 months ago
  2. astimezone template tag by whardier 2 years, 2 months ago
  3. UTC-based astimezone filter by miracle2k 1 year, 6 months ago
  4. Encoding datetime for JSON consumers like YUI by acdha 3 years, 5 months ago
  5. Querying datetime aware objects in your local timezone by jayliew 11 months, 4 weeks ago

Comments

derelm (on April 21, 2007):

i think a cleaner solution would be to pass the timezone as a parameter and not a user instance. the drawback would be more writing-work in your templates...

just my 2cents

#

menendez (on June 5, 2008):

When using this filter I noticed that it was not converting time properly with naive dates between 'America/Chicago' and America/Sao_Paulo. It was adding an extra hour. To add the timezone to a naive date you should do something like this for line 28 (result = val..):

value = pytz.timezone(settings.TIME_ZONE).localize(value) result = value.astimezone(pytz.timezone(tz))

#

(Forgotten your password?)