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