比方說,我有一個字符串,如'2:19.83 blah blah...blah blah'
,格式爲minutes:seconds.centiseconds blah...
和blah
可以表示除換行符以外的任何字符序列。Python:將經過的時間(分鐘:秒)解析爲秒
我想解析並獲得向下舍入的秒數。所以在上面的例子中,結果是139
。
這樣做的最好方法是什麼?
比方說,我有一個字符串,如'2:19.83 blah blah...blah blah'
,格式爲minutes:seconds.centiseconds blah...
和blah
可以表示除換行符以外的任何字符序列。Python:將經過的時間(分鐘:秒)解析爲秒
我想解析並獲得向下舍入的秒數。所以在上面的例子中,結果是139
。
這樣做的最好方法是什麼?
我首先從字符串
>>> newstring=s.split('.',1)[0]
那我就用strptime讀它得到的時間部分...
>>> tt=time.strptime(newstring,"%M:%S")
,最後,在數秒的時間。
>>> tt.tm_min * 60 + tt.tm_sec
不是1套,但很簡單...
sum(x*y for x,y in zip(map(int, re.findall(r'^(\d+):(\d+)', string)[0]), [60,1]))
1醜陋但功能單行。 – Muhd
這似乎是你所需要的:
>>> 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
這件怎麼樣?也許我承認這不是特別漂亮,但功能強大,容易理解我的想法。
鑑於
s = '2:19.83'
和
tmp = s.split(':')
min = int(tmp[0])
sec = int(tmp[1].split('.')[0])
total_secs = min * 60 + sec
print total_secs
產生
139
它應該是:'tt = time.strptime(s,'%M:%S')',%m是個月,%s無效 – Boud
@Boud - 謝謝。這是我沒有仔細查看格式代碼的結果。 – mgilson