Converting ISO 8601 date time to seconds in Python
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 :)
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).