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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With