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 s
import time
from datetime import datetime
t1 = datetime.now().replace(microsecond=0)
time.sleep(3)
now = datetime.now().replace(microsecond=0)
print((now - t1).total_seconds())
result: 3.0
There is always parsing by hand
>>> import re
>>> ts = ['00:00:00,000', '00:00:10,000', '00:01:04,000', '01:01:09,000']
>>> for t in ts:
... times = map(int, re.split(r"[:,]", t))
... print t, times[0]*3600+times[1]*60+times[2]+times[3]/1000.
...
00:00:00,000 0.0
00:00:10,000 10.0
00:01:04,000 64.0
01:01:09,000 3669.0
>>>
without imports
time = "01:34:11"
sum(x * int(t) for x, t in zip([3600, 60, 1], time.split(":")))
It looks like you're willing to strip fractions of a second... the problem is you can't use '00' as the hour with %I
>>> time.strptime('00:00:00,000'.split(',')[0],'%H:%M:%S')
time.struct_time(tm_year=1900, tm_mon=1, tm_mday=1, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=0, tm_yday=1, tm_isdst=-1)
>>>
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.
Inspired by sverrir-sigmundarson's comment:
def time_to_sec(time_str):
return sum(x * int(t) for x, t in zip([1, 60, 3600], reversed(time_str.split(":"))))