Skip to main content
 首页 » 编程设计

Python:将耗时(分:秒)解析为秒

2025年05月04日10lyhabc

假设我有一个类似 '2:19.83 blah blah...blah blah' 的字符串,其中格式为 minutes:seconds.centiseconds blah... 并且blah 可以表示除换行符之外的任何字符序列。

我想解析并获取向下舍入的秒数。所以在上面的示例中,结果将是 139。

执行此操作的最佳方法是什么?

请您参考如下方法:

我会先从字符串中获取时间部分

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

然后我会使用 strptime 读取它...

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

最后,以秒为单位获取时间。

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

不是 1-liner,但很简单......