Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting ISO 8601 date time to seconds in Python

Tags:

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?

like image 301
Zaynaib Giwa Avatar asked Dec 02 '14 09:12

Zaynaib Giwa


People also ask

How do you convert date and time to seconds in Python?

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.

How do I convert ISO to datetime in Python?

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'.

Does ISO 8601 have milliseconds?

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).


1 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 :)

like image 144
chunpoon Avatar answered Sep 20 '22 17:09

chunpoon