Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Another converting hh:mm:ss to seconds

Tags:

python

I have seen a few questions that want the same except in my situation the time format isn't always hh:mm:ss, sometimes it's just mm:ss

I understand the idea mentioned here How to convert an H:MM:SS time string to seconds in Python? and here Python Time conversion h:m:s to seconds

What i don't understand is how to deal with situations like hh:mm:ss, h:mm:ss, mm:ss or just m:ss

def getSec(s):
    l = s.split(':')
    return int(l[0]) * 3600 + int(l[1]) * 60 + int(l[2])

Edit: I think my question isn't clear enough. I'm searching for a solution to handle all possible formats with 1 single function.

like image 279
user1987032 Avatar asked Dec 08 '22 14:12

user1987032


1 Answers

def getSec(s):
    l = map(int, s.split(':')) # l = list(map(int, s.split(':'))) in Python 3.x
    return sum(n * sec for n, sec in zip(l[::-1], (1, 60, 3600)))

getSec('20') # 20
getSec('1:20') # 80
getSec('1:30:01') # 5401
like image 99
falsetru Avatar answered Dec 31 '22 02:12

falsetru