Converting ISO 8601 date time to seconds in Python

Question:

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?

Asked By: Zaynaib Giwa

||

Answers:

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 🙂

Answered By: chunpoon

Your date is UTC time in RFC 3339 format, you could parse it using only stdlib:

from datetime import datetime

utc_dt = datetime.strptime('1984-06-02T19:05:00.000Z', '%Y-%m-%dT%H:%M:%S.%fZ')

# Convert UTC datetime to seconds since the Epoch
timestamp = (utc_dt - datetime(1970, 1, 1)).total_seconds()
# -> 455051100.0

See also Converting datetime.date to UTC timestamp in Python

How do I convert it back to ISO 8601 format?

To convert POSIX timestamp back, create a UTC datetime object from it, and format it using .strftime() method:

from datetime import datetime, timedelta

utc_dt = datetime(1970, 1, 1) + timedelta(seconds=timestamp)
print(utc_dt.strftime('%Y-%m-%dT%H:%M:%S.%fZ'))
# -> 1984-06-02T19:05:00.000000Z

Note: It prints six digits after the decimal point (microseconds). To get three digits, see Formatting microseconds to 2 decimal places (in fact converting microseconds into tens of microseconds).

Answered By: jfs

Here is a solution in Python 3:

$ date +%s
1428030452
$ TZ=US/Pacific date -d @1428030452 '+%Y%m%d %H:%M:%S %z'
20150402 20:07:32 -0700
$ TZ=US/Eastern date -d @1428030452 '+%Y%m%d %H:%M:%S %z'
20150402 23:07:32 -0400
$ python3
>>> from datetime import datetime,timezone
>>> def iso2epoch(ts):
...     return int(datetime.strptime(ts[:-6],"%Y%m%d %H:%M:%S").replace(tzinfo=timezone.utc).timestamp()) - (int(ts[-2:])*60 + 60 * 60 * int(ts[-4:-2]) * int(ts[-5:-4]+'1'))
...
>>> iso2epoch("20150402 20:07:32 -0700")
1428030452
>>> iso2epoch("20150402 23:07:32 -0400")
1428030452
>>>
Answered By: toppk