Login

isoutc template filter

Author:
japerk
Posted:
April 9, 2009
Language:
Python
Version:
1.0
Tags:
datetime utc
Score:
0 (after 0 ratings)

Use this template filter to produce an ISO format UTC datetime string from a timezone aware datetime object. Usage example in a template: <input name="when" type="hidden" value="{{ dt|isoutc }}". You must have dateutil installed for tz.tzutc() to work. And of course, you'll need to load it as a custom tag to use it.

The output format differs from python's datetime.isoformat by ignoring the microsecond and including a "Z" suffix for the UTC timezone. For ease of use, it is also not double quoted as the standard suggests.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
from django import template
from dateutil import tz
import datetime

register = template.Library()

@register.filter
def isoutc(value):
    if value and isinstance(value, datetime.datetime):
        return value.astimezone(tz.tzutc()).strftime('%Y-%m-%dT%H:%M:%SZ')
    else:
        return value

More like this

  1. timeto template filter by japerk 6 years, 1 month ago
  2. JSON encode ISO UTC datetime by japerk 6 years, 1 month ago
  3. Template tags for localizing UTC times with pytz by wolever 3 years, 9 months ago
  4. UTC-based astimezone filter by miracle2k 3 years, 6 months ago
  5. JSON decode datetime by japerk 6 years, 1 month ago

Comments

Please login first before commenting.