Created
August 7, 2013 17:25
-
-
Save danielrichman/6176316 to your computer and use it in GitHub Desktop.
pretty python datetime formatting
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
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