Kiran Gangadharan

Dealing with ISO 8601 dates in Python

· Kiran Gangadharan

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:

1
2
3
>>> 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:

1
2
3
4
>>> 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:

1
2
3

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