Return a datetime corresponding to date_string, parsed according to format.
I had the need for such a thing while working with an API that returned JSON that I fed, via simplejson, directly to a template, and didn't want to change the data structure just for this one piece.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | import datetime
from django.template import Library
from django.template.defaultfilters import stringfilter
register = Library()
@stringfilter
def parse_date(date_string, format):
"""
Return a datetime corresponding to date_string, parsed according to format.
For example, to re-display a date string in another format::
{{ "01/01/1970"|parse_date:"%m/%d/%Y"|date:"F jS, Y" }}
"""
try:
return datetime.datetime.strptime(date_string, format)
except ValueError:
return None
register.filter(parse_date)
|
More like this
- Template tag - list punctuation for a list of items by shapiromatron 10 months, 2 weeks ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 3 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
- Help text hyperlinks by sa2812 1 year, 6 months ago
Comments
this is what i eventually did for django 1.11
from datetime import datetime from django import template from django.template.defaultfilters import stringfilter
register = template.Library() @register.filter(name='parse_date') @stringfilter def parse_date(date_string): """ Return a datetime corresponding to date_string, parsed according to format.
#
Please login first before commenting.