Skip to content

Instantly share code, notes, and snippets.

@danielrichman
Created August 7, 2013 17:25
Show Gist options
  • Save danielrichman/6176316 to your computer and use it in GitHub Desktop.
Save danielrichman/6176316 to your computer and use it in GitHub Desktop.
pretty python datetime formatting
def format_datetime(datetime, format_name="nice short",
custom_format=None, convert_bst=True):
"""
Jinja2 filter to turn a datetime into a string
`datetime` must be timezone-naive (as far as python is concerned),
but its values must be UTC.
Either pick `format_name` from the options below, or provide
`custom_format`
* ``full+tz``: 2013-08-07 18:23:46 BST+0100
* ``full``: 2013-08-07 18:24:12
* ``nice``: Wednesday 07 August 2013 at 18:24:37
* ``nice short``: Wed 07 Aug at 18:24
* ``date``: 2013-08-07
* ``date nice``: Wednesday 07 August 2013
* ``date nice short``: Wed 07 Aug
"""
formats = {
"full+tz": "%Y-%m-%d %H:%M:%S %Z%z",
"full": "%Y-%m-%d %H:%M:%S",
"nice": "%A %d %B %Y at %H:%M:%S",
"nice short": "%a %d %b at %H:%M",
"date": "%Y-%m-%d",
"date nice": "%A %d %B %Y",
"date nice short": "%a %d %b",
}
if custom_format is not None:
format = custom_format
else:
format = formats[format_name]
datetime = pytz.utc.localize(datetime)
if convert_bst:
datetime = datetime.astimezone(pytz_bst)
return datetime.strftime(format)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment