Python将时间持续时长转换为秒

0 投票
4 回答
894 浏览
提问于 2025-04-17 22:05

我正在使用一个外部程序,它输出的时间格式是这样的。

15mn
1h 15mn 3sc
34 sc

我该如何把所有这样的字符串转换成秒呢?比如说(15分钟 = 900秒)?

4 个回答

0

我在找其他东西的时候偶然发现了这个。这里有一个更简单、更干净的解决方案,使用的是Python Pints

import pint
ureg = pint.UnitRegistry()

ureg.define("mn = minutes") # Define non-standard units
ureg.define("sc = seconds")
ureg.define("h = hours")

def parse_odd_time_format(s):
    duration = ureg("0 seconds") # Just something to initialize
    for x in s.split(" "):
        duration += ureg(x) # Parse all the bits and add them together 
    return duration.magnitude # Split off the seconds

parse_odd_time_format("1h 15mn 3sc")
0

我用一个(相当复杂的 :)) 正则表达式来解析你的字符串。

>>> def s_to_secs(s):
        import re
        mat = re.match(r"((?P<hours>\d+)\s?h)?\s?((?P<minutes>\d+)\s?mn)?\s?((?P<seconds>\d+)\s?sc)?", s)
        secs = 0
        secs += int(mat.group("hours"))*3600 if mat.group("hours") else 0
        secs += int(mat.group("minutes"))*60 if mat.group("minutes") else 0
        secs += int(mat.group("seconds")) if mat.group("seconds") else 0
        return secs
>>> for s in ("15mn", "1h 15mn 3sc", "34 sc"):
        print(s_to_secs(s))
900
4503
34
1

使用一个 re 和一个 dict 来获取一个倍数,比如:

import re

text = '1h 15mn 3sc'
in_seconds = {'h': 60 * 60, 'mn': 60, 'sc': 1}
seconds = sum(int(num) * in_seconds[weight] for num, weight in re.findall(r'(\d+)\s?(mn|sc|h)', text))
# 4503

需要注意的是,这种方法允许像 "1h 3mn 5h 3sc 12mn 2h 5sc" 这样的结构,所以可能并不是大家想要的...

1

再来一个:

如果你只需要写一个函数,这个函数可以提取带有特定标签的数字……

def fs(x, p):
     p = re.sub('\s+', '', p) # get rid of spaces ...
     if re.search('[0-9]+'+x, p): # exp = (n digits) + (tag 'x') 
         return int( re.search('[0-9]+'+x, p).group()[:-len(x)] )
     else: return 0

那么你之后就可以直接用这些数字进行计算了……

def toSec(p): return fs('h',p)*3600 + fs('mn',p)*60 + fs('sc',p)

撰写回答