2012-04-30 34 views
0

比方說,我有一個字符串,如'2:19.83 blah blah...blah blah',格式爲minutes:seconds.centiseconds blah...blah可以表示除換行符以外的任何字符序列。Python:將經過的時間(分鐘:秒)解析爲秒

我想解析並獲得向下舍入的秒數。所以在上面的例子中,結果是139

這樣做的最好方法是什麼?

回答

4

我首先從字符串

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

那我就用strptime讀它得到的時間部分...

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

,最後,在數秒的時間。

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

不是1套,但很簡單...

+1

它應該是:'tt = time.strptime(s,'%M:%S')',%m是個月,%s無效 – Boud

+0

@Boud - 謝謝。這是我沒有仔細查看格式代碼的結果。 – mgilson

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

1醜陋但功能單行。 – Muhd

1

這似乎是你所需要的:

>>> 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 
+0

這給我一個酸洗錯誤,使用http://shell.appspot.com/ – Muhd

+0

上的python shell。正如你所看到的,它可以在我的Python 2.7 shell中工作。這是一個複製/粘貼。我無法解釋你的酸洗錯誤。 – alan

+0

可能是python 2.5的一個問題...當我有機會的時候,我會在我家的電腦上看到它。 – Muhd

2

這件怎麼樣?也許我承認這不是特別漂亮,但功能強大,容易理解我的想法。

鑑於

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 
+1

我認爲這比一個正則表達式更漂亮...正則表達式很好,但是在這種情況下(並且很難閱讀)它是過度的。 – mgilson

+0

對不起我的評論,但自從我提出了正則表達式的解決方案,我有權說'你是對的!我也更喜歡這個。 +1 – alan

+0

謝謝..我有限的知識經常讓我「簡單勝過複雜」。方案:) – Levon