Login

parse date template tag

Author:
robhudson
Posted:
October 13, 2009
Language:
Python
Version:
1.1
Tags:
datetime parse strptime
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

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.