Converting ISO 8601 date time to seconds in Python

Zaynaib Giwa picture Zaynaib Giwa · Dec 2, 2014 · Viewed 29.4k times · Source

I am trying to add two times together. The ISO 8601 time stamp is '1984-06-02T19:05:00.000Z', and I would like to convert it to seconds. I tried using the Python module iso8601, but it is only a parser.

Any suggestions?

Answer

heyitschun picture heyitschun · Dec 2, 2014

If you want to get the seconds since epoch, you can use python-dateutil to convert it to a datetime object and then convert it so seconds using the strftime method. Like so:

>>> import dateutil.parser as dp
>>> t = '1984-06-02T19:05:00.000Z'
>>> parsed_t = dp.parse(t)
>>> t_in_seconds = parsed_t.timestamp()
>>> t_in_seconds
'455051100'

So you were halfway there :)