简体   繁体   中英

Python: Parse elapsed time (minutes : seconds) to seconds

Let's say I have a string like '2:19.83 blah blah...blah blah' where the format is minutes:seconds.centiseconds blah... and blah can represent any sequence of characters other than a newline.

I want to parse and get the number of seconds rounded down. So in the above example, the result would be 139 .

What is the best way to do this?

I would first get the time portion from the string

>>> newstring=s.split('.',1)[0]

Then I would read it using strptime...

>>> tt=time.strptime(newstring,"%M:%S")

and then finally, get the time in seconds.

>>> tt.tm_min * 60 + tt.tm_sec

Not a 1-liner, but pretty simple...

sum(x*y for x,y in zip(map(int, re.findall(r'^(\d+):(\d+)', string)[0]), [60,1]))

How about this one? Not particularly pretty perhaps I admit, but functional and easy to comprehend I think.

Given

s = '2:19.83'

and

tmp = s.split(':')
min = int(tmp[0])
sec = int(tmp[1].split('.')[0])

total_secs = min * 60 + sec   
print total_secs

yields

139

This seems to do what you need:

>>> s = '2:19.83 blah blah...blah blah'
>>> import re
>>> m = re.match(r'(?P<min>\d):(?P<sec>\d{2})\.\d+', s)
>>> if m:
...     seconds = (int(m.group('min')) * 60) + int(m.group('sec'))
...     print seconds
139

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM