Parsing ISO 8601 timestamps in plain Django
“How do I parse an ISO 8601 formatted date in Django without bringing in extra dependencies?”
If you do any web development with Python and Django then you’ll inevitable find yourself wanting to parse ISO 8601 timestamps into Python’s native datetime.datetime
objects at some point. In other words, given a timestamp string like '2016-12-11T09:27:24.895'
we want to convert it into a proper Python datetime
object for further processing.
If you search Google on how to do this you’ll often find people recommend the 3rd party python-dateutil module. Python-dateutil is a great choice – but in some cases it does more than you really need.
If you’re already using Django you can parse ISO 8601 timestamps without bringing in another dependency using django.utils.dateparse.parse_datetime.
Here’s how:
from django.utils.dateparse import parse_datetime parsed = parse_datetime('2001-12-11T09:27:24.895551') assert parsed == datetime(2001, 12, 11, 9, 27, 20, 608645)
Note that if you pass a malformed value to parse_datetime
it can throw a KeyError
, ValueError
, or TypeError
exception so you might want to be ready to handle those.
Importantly, parse_datetime
also understands timezone-aware timestamps and correctly sets the UTC offset on the resulting datetime
object:
from django.utils.dateparse import parse_datetime from django.utils.timezone import is_aware, utc expected = datetime.datetime(2016, 4, 27, 11, 18, 42, 303886, tzinfo=utc) parsed = parse_datetime('2016-04-27T11:18:42.303886+00:00') assert parsed == expected assert is_aware(parsed)