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

Discussão em 'Python' iniciado por Stack, Junho 22, 2025.

  1. Stack

    Stack Membro Participativo

    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

    Continue reading...

Compartilhe esta Página