Muhd
Muhd

Reputation: 25566

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?

Upvotes: 1

Views: 2347

Answers (4)

mgilson
mgilson

Reputation: 309831

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...

Upvotes: 5

alan
alan

Reputation: 4842

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

Upvotes: 1

Levon
Levon

Reputation: 143037

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

Upvotes: 3

JBernardo
JBernardo

Reputation: 33387

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

Upvotes: 2

Related Questions