Login

parse date template tag

Author:
robhudson
Posted:
October 13, 2009
Language:
Python
Version:
1.1
Score:
2 (after 2 ratings)

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

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

Comments

hakimkal (on November 19, 2017):

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.

For example, to re-display a date string in another format::

    {{ "01/01/1970"|parse_date }}

"""
try:
    print("\n\n\n The return value ")
    print(datetime.strptime(date_string, '%Y-%m-%dT%H:%M:%S+0000'))
    return datetime.strptime(date_string, '%Y-%m-%dT%H:%M:%S+0000')
except ValueError:
    return None

#

Please login first before commenting.