Login

isoutc template filter

Author:
japerk
Posted:
April 9, 2009
Language:
Python
Version:
1.0
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. Django Settings Assignment Expressions aka Walrus Operator example by webology 2 weeks, 5 days ago
  2. codigo alto nivel by MrRocklion 2 months, 2 weeks ago
  3. Load template from specific app by Krzysiek555 3 months ago
  4. PostgreSQL JSON subqueries by dolamroth 3 months, 1 week ago
  5. "Magic Link" Management Command by webology 8 months, 1 week ago

Comments

Please login first before commenting.