pythondatetimetimeiso8601

convert ISO8601 format to seconds in python without using any external library


I am trying to convert ISO8601 time format to seconds/unix/epoch time in python with just using the standard library.

Time format = '2012-09-30T15:31:50.262-08:00'

Basically the time will be a string which it parses and converts it back to seconds.

Slicing and picking the values which we want is possible but is there any better way than this?

import datetime, time
def convert_enddate_to_seconds(self, ts):
    """Takes ISO 8601 format(string) and converts into epoch time."""
     dt = datetime.datetime.strptime(ts[:-7],'%Y-%m-%dT%H:%M:%S.%f')+\
                datetime.timedelta(hours=int(ts[-5:-3]),
                minutes=int(ts[-2:]))*int(ts[-6:-5]+'1')
    seconds = time.mktime(dt.timetuple()) + dt.microsecond/1000000.0
    return seconds

Solution

  • The final correct answer after Celada's answer. Below I have verified that the outputs of both the xml.iso8601.parse also returns the same result as the one generated by the function. Thanks to Celada for providing issues with the original code.

    >>> import calendar, datetime, time 
    >>> def convert_enddate_to_seconds(ts):
    ...   """Takes ISO 8601 format(string) and converts into epoch time."""
    ...   dt = datetime.datetime.strptime(ts[:-7],'%Y-%m-%dT%H:%M:%S.%f')-\
    ...       datetime.timedelta(hours=int(ts[-5:-3]),
    ...       minutes=int(ts[-2:]))*int(ts[-6:-5]+'1')
    ...   seconds = calendar.timegm(dt.timetuple()) + dt.microsecond/1000000.0
    ...   return seconds
    ... 
    >>> import iso8601
    >>> ts = '2012-09-30T15:31:50.262-08:00'
    >>> iso8601.parse(ts)
    1349047910.0
    >>> convert_enddate_to_seconds(ts)
    1349047910.26
    >>>