从python中的H mn s格式时间中提取值

时间:2012-10-22 20:47:13

标签: python regex time

我想用一些正则表达式从时间值中提取这种数据:

1h 34mn 2s     >>> [1,34,2]
1h 4mn         >>> [1,4]
34mn 2s        >>> [34,2]
34s            >>> [34]

我试过:

re.match(r'((.*)h)?((.*)mn)?((.*)s)?', '1h 34mn').groups()
('1h', '1', ' 34mn', ' 34', None, None)

几乎已经完成,但仍然不是我正在寻找的。

编辑:

我需要以秒为单位提取总值1h 34mn 2s >>> 1*3600+34*60+2

4 个答案:

答案 0 :(得分:5)

好吧,如果您只想要几秒钟,并且不太担心小时数在分钟之前,而分钟在几秒之前,只要它们合格(即'1s 9h 32m'有效),您就可以使用方法:

import re

mult = {'h': 60*60, 'mn': 60}
res = sum(int(num) * mult.get(val, 1) for num, val in re.findall('(\d+)(\w+)', '1h 34mn 2s'))
# 5642

答案 1 :(得分:2)

如果数据与您的示例相同,您只需执行以下操作:

In [171]: import re

In [172]: s='1h 34mn 2s'

In [173]: re.findall('\d+',s)
Out[173]: ['1', '34', '2']

或者如果你想要int

In [175]: [int(i)for i in re.findall('\d+',s)]
Out[175]: [1, 34, 2]

答案 2 :(得分:1)

试试这个:

[in] regex = re.compile(r'^(?:(\d+)h)?(?: *)(?:(\d+)mn)?(?: *)(?:(\d+)s)?$')
[in] for x in ("1h 34mn 2s", "1h 4mn", "34mn 2s", "34s"):
[in]     hours, minutes, seconds = regex.match(x).groups()
[in]     total = 0
[in]     if hours:
[in]         total += int(hours) * 3600
[in]     if minutes:
[in]         total += int(minutes) * 60
[in]     if seconds:
[in]         total += int(seconds)
[in]     print total

[out] 5642
[out] 3840
[out] 2042
[out] 34

刚刚意识到你并没有在每次输入上寻找三重奏。现在修好了。

答案 3 :(得分:0)

KISS

import re

a = ['1h 34mn 2s','1h 4mn','34mn 2s','34s']

def convert(s):
    if s:
        return int(s[0])
    else:
        return 0

def get_time(a):
    h = convert(re.findall('(\d*)h',a))
    m = convert(re.findall('(\d*)m',a))
    s = convert(re.findall('(\d*)s',a))
    return h,m,s

for i in a:
    print get_time(i)

输出:

(1, 34, 2)
(1, 4, 0)
(0, 34, 2)
(0, 0, 34)

EDIT。我刚刚看到,你想要几秒钟的日期。您只需将 get_time 函数中的返回行编辑为:

return h*3600+m*60+s

输出:

5642
3840
2042
34