[英]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. 假设我有一个像
'2:19.83 blah blah...blah blah'
这样的字符串,其格式为minutes:seconds.centiseconds blah...
并且blah
可以表示除换行符以外的任何字符序列。
I want to parse and get the number of seconds rounded down. 我想解析并获取四舍五入的秒数。 So in the above example, the result would be
139
. 因此,在上面的示例中,结果将为
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... 然后我会使用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... 不是1线,而是非常简单...
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.