How to convert an H:MM:SS time string to seconds in Python?

Basically I have the inverse of this problem: Python Time Seconds to h:m:s

I have a string in the format H:MM:SS (always 2 digits for minutes and seconds), and I need the integer number of seconds that it represents. How can I do this in python?

For example:

  • "1:23:45" would produce an output of 5025
  • "0:04:15" would produce an output of 255
  • "0:00:25" would produce an output of 25

etc


Solution 1:

def get_sec(time_str):
    """Get Seconds from time."""
    h, m, s = time_str.split(':')
    return int(h) * 3600 + int(m) * 60 + int(s)


print(get_sec('1:23:45'))
print(get_sec('0:04:15'))
print(get_sec('0:00:25'))

Solution 2:

ts = '1:23:45'
secs = sum(int(x) * 60 ** i for i, x in enumerate(reversed(ts.split(':'))))
print(secs)

Solution 3:

Using datetime module

import datetime
t = '10:15:30'
h,m,s = t.split(':')
print(int(datetime.timedelta(hours=int(h),minutes=int(m),seconds=int(s)).total_seconds()))

Output: 36930

Solution 4:

Without many checks, and assuming it's either "SS" or "MM:SS" or "HH:MM:SS" (although not necessarily two digits per part):

def to_seconds(timestr):
    seconds= 0
    for part in timestr.split(':'):
        seconds= seconds*60 + int(part, 10)
    return seconds

>>> to_seconds('09')
9
>>> to_seconds('2:09')
129
>>> to_seconds('1:02:09')
3729

This is a different “spelling” of FMc's answer :)

Solution 5:

Using datetime module is also posible and more robust

import datetime as dt

def get_total_seconds(stringHMS):
   timedeltaObj = dt.datetime.strptime(stringHMS, "%H:%M:%S") - dt.datetime(1900,1,1)
   return timedeltaObj.total_seconds()

datetime.strptime parses the string according to format %H:%M:%S, and it creates a datetime object as year 1900, month1, day 1, hour H, minute M, and second S.

That's why to get the total of seconds is necessary to subtract the year, month and day.

print(get_total_seconds('1:23:45'))
>>> 5025.0

print(get_total_seconds('0:04:15'))
>>> 255.0

print(get_total_seconds('0:00:25'))
>>>25.0