Skip to content

Instantly share code, notes, and snippets.

@bycoffe
Created October 31, 2009 20:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bycoffe/223228 to your computer and use it in GitHub Desktop.
Save bycoffe/223228 to your computer and use it in GitHub Desktop.
from django.template import Library
register = Library()
@register.filter_function
def html5datetime(date):
"""Format a date or a date and time according to the HTML 5 specifications,
so it may be used as the value for a datetime attribute of a time tag.
Most of the date formatting could be done in the template with the built-in
date filter, but HTML 5 requires the time-zone offset to be in the format
HH:MM, and this is not possible to do with the built-in filter.
See http://www.whatwg.org/specs/web-apps/current-work/multipage/common-microsyntaxes.html#valid-global-date-and-time-string
>>> import datetime
>>> date = datetime.datetime(2009, 10, 31, 16, 4, 17, 428896)
>>> print html5datetime(date) # doctest:+ELLIPSIS
2009-10-31T16:04:17...:...
>>> print html5datetime(date.date())
2009-10-31
"""
import re
from django.utils.dateformat import DateFormat
# If this is just a date and not a datetime, we can just
# return return the date as YYYY-MM-DD and don't have to
# worry about the extra requirements of the HTML 5 specs.
if not hasattr(date, 'hour'):
return date.strftime('%Y-%m-%d')
formatter = DateFormat(date)
offset = formatter.O()
match = re.match(r'(?P<start>[-+]\d\d)(?P<end>\d\d)', offset)
if not match:
return ''
return date.strftime('%Y-%m-%dT%H:%M:%S%%s') % ':'.join(match.groups())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment