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

Comments

Please login first before commenting.