parse_date.py 782 Bytes
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
import datetime

from django.template import Library
from django.template.defaultfilters import stringfilter

register = Library()

@stringfilter
def parse_date(date_string, format="%Y-%m-%dT%H:%M:%S"):
    """
    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


@stringfilter
def parse_date_fancy(date_string):
    try:
        return parse_date(date_string).strftime("%l %d %F, %H:%i %a")
    except ValueError:
        return None

register.filter(parse_date)
register.filter(parse_date_fancy)