在python中将时间字符串XhYmZs转换为秒

AJW*_*AJW 2 python python-2.7

我有一个字符串,它有三种形式:

XhYmZs or YmZs or Zs
Run Code Online (Sandbox Code Playgroud)

其中,h,m,s 表示小时、分钟、秒,X、Y、Z 是相应的值。

如何在 python2.7 中有效地将这些字符串转换为秒?

我想我可以做这样的事情:

s="XhYmZs"
if "h" in s:
    hours=s.split("h")
elif "m" in s:
    mins=s.split("m")[0][-1]
Run Code Online (Sandbox Code Playgroud)

...但这对我来说似乎不是很有效:(

Tig*_*kT3 6

在您感兴趣的分隔符上拆分,然后将每个结果元素解析为一个整数并根据需要相乘:

import re
def hms(s):
    l = list(map(int, re.split('[hms]', s)[:-1]))
    if len(l) == 3:
        return l[0]*3600 + l[1]*60 + l[2]
    elif len(l) == 2:
        return l[0]*60 + l[1]
    else:
        return l[0]
Run Code Online (Sandbox Code Playgroud)

这会产生标准化为秒的持续时间。

>>> hms('3h4m5s')
11045
>>> 3*3600+4*60+5
11045
>>> hms('70m5s')
4205
>>> 70*60+5
4205
>>> hms('300s')
300
Run Code Online (Sandbox Code Playgroud)

您还可以通过将re.split()结果翻转并乘以 60 以基于元素在列表中的位置递增的幂来制作这一行:

def hms2(s):
    return sum(int(x)*60**i for i,x in enumerate(re.split('[hms]', s)[-2::-1]))
Run Code Online (Sandbox Code Playgroud)