Quantcast
Channel: Planet Python
Viewing all articles
Browse latest Browse all 22835

Daniel Bader: Parsing ISO 8601 timestamps in plain Django

$
0
0

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 also a very comprehensive solution.

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:

fromdjango.utils.dateparseimportparse_datetimeparsed=parse_datetime('2001-12-11T09:27:24.895551')assertparsed==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:

fromdjango.utils.dateparseimportparse_datetimefromdjango.utils.timezoneimportis_aware,utcexpected=datetime.datetime(2016,4,27,11,18,42,303886,tzinfo=utc)parsed=parse_datetime('2016-04-27T11:18:42.303886+00:00')assertparsed==expectedassertis_aware(parsed)

Viewing all articles
Browse latest Browse all 22835

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>