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?
Use the datetime. timetuple() to get the time tuple from datetime. Next, pass the time tuple to the calendar. timegm() method to convert datetime to seconds.
To get an ISO 8601 date in string format in Python 3, you can simply use the isoformat function. It returns the date in the ISO 8601 format. For example, if you give it the date 31/12/2017, it'll give you the string '2017-12-31T00:00:00'.
ISO 8601 represents date and time by starting with the year, followed by the month, the day, the hour, the minutes, seconds and milliseconds. For example, 2020-07-10 15:00:00.000, represents the 10th of July 2020 at 3 p.m. (in local time as there is no time zone offset specified—more on that below).
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 :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With