How to convert a time string to seconds?
I need to convert time value strings given in the following format to seconds, for example:
1.'00:00:00,000' -> 0 seconds
2.'00:00:10,000' -> 10 seconds
3.'00:01:04,000' -> 64 seconds
4.'01:01:09,000' -> 3669 seconds
Do I need to use regex to do this? I tried to use the time module, but
time.strptime('00:00:00,000','%I:%M:%S')
throws:
ValueError: time data '00:00:00,000' does not match format '%I:%M:%S'
Edit:
Looks like this:
from datetime import datetime
pt = datetime.strptime(timestring,'%H:%M:%S,%f')
total_seconds = pt.second + pt.minute*60 + pt.hour*3600
gives the correct result. I was just using the wrong module.
>>> import datetime
>>> import time
>>> x = time.strptime('00:01:00,000'.split(',')[0],'%H:%M:%S')
>>> datetime.timedelta(hours=x.tm_hour,minutes=x.tm_min,seconds=x.tm_sec).total_seconds()
60.0
A little more pythonic way I think would be:
timestr = '00:04:23'
ftr = [3600,60,1]
sum([a*b for a,b in zip(ftr, map(int,timestr.split(':')))])
Output is 263Sec.
I would be interested to see if anyone could simplify it further.
without imports
time = "01:34:11"
sum(x * int(t) for x, t in zip([3600, 60, 1], time.split(":")))