I need to convert time value strings given in the following format to seconds.I am using python2.6
eg:
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 time module,but time.strptime('00:00:00,000','%I:%M:%S')
threw
ValueError: time data '00:00:00,000' does not match format '%I:%M:%S'
Can someone tell me how this can be solved?
Edit:
I think
pt =datetime.datetime.strptime(timestring,'%H:%M:%S,%f')
total_seconds = pt.second+pt.minute*60+pt.hour*3600
gives the correct value..I was using the wrong module
To get the
timedelta()
, you should subtract1900-01-01
:%H
above implies the input is less than a day, to support the time difference more than a day:To emulate
.total_seconds()
on Python 2.6:result: 3.0
A little more pythonic way I think would be:
Output is 263Sec.
I would be interested to see if anyone could simplify it further.
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
For Python 2.7:
There is always parsing by hand