Created
October 8, 2009 23:47
-
-
Save robhudson/205541 to your computer and use it in GitHub Desktop.
parse_date template tag
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment