Code

Ticket #3378: astimezone.py

File astimezone.py, 755 bytes (added by arvin, 7 years ago)

datetime convert filter

Line 
1"""
2Timezone converter for Django.  This  filter converts a datetime from UTC to
3the specified timezone.  If the specified timezone is unknown the filter
4fails silently and returns the original datetime.
5
6Requires the Python-timezone library (pytz) from http://pytz.sourceforge.net/.
7"""
8
9from datetime import datetime
10from pytz import timezone, utc
11from django import template
12
13register = template.Library ()
14
15@register.filter
16def astimezone (value, arg):
17
18    try:
19        tz = timezone (arg)
20    except KeyError:
21        return value
22
23    value_utc = datetime (value.year, value.month, value.day,
24                          value.hour, value.minute, value.second,
25                          value.microsecond, utc)
26
27    return value_utc.astimezone (tz)
28