pythonpython-2.7timeiso8601rfc3339

Converting ISO 8601 date time to seconds in Python


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?


Solution

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