Dan Bader

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)

Which frameworks and libraries are the most important to know to be considered an effective Python dev? Here’s how you go from “writing scripts” to “building applications” with Python, master the tools of the trade for Dependency Management, and become an expert at picking quality Python libraries: » Click here to learn more

Improve Your Python with a fresh 🐍 Python Trick 💌 every couple of days

🔒 No spam ever. Unsubscribe any time.

This article was filed under: django, python, and web-development.

Related Articles:
Latest Articles:

Peer-to-Peer Learning for Pythonistas PythonistaCafe is an invite-only, online community of Python and software development enthusiasts helping each other succeed and grow: » Learn more at pythonistacafe.com

← Browse All Articles