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

  1. Parse datetime model field to string by jzelez 4 years, 8 months ago
  2. Natural language date/time form fields by jdriscoll 7 years, 9 months ago
  3. Template-Filter for Feedparser-Dates by kioopi 5 years, 9 months ago
  4. Human format Date representation by sachingupta006 3 years ago
  5. Parsed RSS into template var by bram 6 years, 8 months ago

Comments

Please login first before commenting.