Dealing with ISO 8601 dates in Python

For those who don’t know what the ISO 8601 format is, you can read about it here.

To create an ISO 8601 timestamp in Python, do:

>>> from datetime import datetime
>>> timestamp = datetime.utcnow().isoformat() + 'Z'
'2014-04-01T15:11:18.195125Z'

The ‘ Z ‘ added to the timestamp indicates that the timezone is UTC.

To parse a ISO 8601 timestamp and generate a datetime  object, do:

>>> import dateutil.parser as dp
>>> a = dp.parse(timestamp)
>>> a
datetime.datetime(2014, 4, 1, 15, 11, 46, 113800, tzinfo=tzutc())

Alternatively, you could also generate the object using:

>>> datetime.strptime(timestamp, '%Y-%m-%dT%H:%M:%S.%fZ')
datetime.datetime(2014, 4, 1, 15, 11, 46, 113800)
Go Top
comments powered by Disqus