繁体   English   中英

如何将“小时、分钟和秒”字符串转换为 HH:MM:SS 格式?

[英]How to convert A "hours and minutes and seconds" string to HH:MM:SS format?

在 python 中,我正在尝试制作一个警报系统,它将“x 小时 y 分钟和 z 秒”转换为 x:y:z 格式例如:

5 hours 20 minutes 6 seconds
05:20:06

1 hour 25 seconds
01:00:25

这是我的代码,但似乎磨损了:

time_string = '1 hour and 25 seconds'

correction = time_string.replace('and ', '')
duration = correction.replace(' hour', ':').replace(' minute', ':').replace(' second', ':').replace(' ','').replace('s', '')
    if 'minute' not in correction and 'second' not in correction:
        duration = duration + '00:00'
    elif 'minute' not in correction and 'second' in correction:
        duration = duration.replace(':',':00:')
    elif 'second' not in correction:
        duration = duration + '00' 
    secs = sum(int(x) * 60 ** i for i, x in enumerate(reversed(duration.split(':'))))

我该如何改进它?

这将返回总秒数,这似乎是您想要的:

def parsex(s):
    hh = mm = ss = 0
    for word in s.split():
        word = word.lower()
        if word.isdigit():
            save = word
        elif word.startswith('hour'):
            hh = int(save)
        elif word.startswith('minute'):
            mm = int(save)
        elif word.startswith('second'):
            ss = int(save)
    return (hh*60+mm)*60+ss

print(parsex('1 hour and 30 seconds'))
print(parsex('2 hours 15 minutes 45 seconds'))

您可以使用 datetime 库将这种类型的字符串转换为正确格式的字符串。

from datetime import datetime

def format_time(string):
    format_string = ''
    if 'hour' in string:
        if 'hours' in string:
            format_string += '%H hours '
        else:
            format_string += '%H hour '
    if 'minute' in string:
        if 'minutes' in string:
            format_string += '%M minutes '
        else:
            format_string += '%M minute '
    if 'second' in string:
        if 'seconds' in string:
            format_string += '%S seconds'
        else:
            format_string += '%S second'
    value = datetime.strptime(string, format_string)
    return value.strftime('%H:%M:%S')

string = '5 hours 20 minutes 6 seconds'
print(format_time(string))

string = '1 hour 25 seconds'
print(format_time(string))

string = '1 minute 25 seconds'
print(format_time(string))

Output

05:20:06
01:00:25
00:01:25
from collections import defaultdict

dataexp = [
("5 hours 20 minutes 6 seconds","05:20:06"),
("1 hour 25 seconds","01:00:25")
]

def convert(input_):
    words = input_.replace('and','').split()
    di = defaultdict(lambda:0)
    while words:
        num = int(words.pop(0))
        unit = words.pop(0)[0]
        di[unit] = num

    return f"{di['h']:02}:{di['m']:02}:{di['s']:02}"

for inp, exp in dataexp:

    got = convert(inp)
    msg = "\nfor %-100.100s \nexp :%s:\ngot :%s:\n" % (inp, exp, got)
    if exp == got:
        print("✅! %s" % msg)
    else:
        print("❌! %s" % msg)

输出:

✅!
for 5 hours 20 minutes 6 seconds
exp :05:20:06:
got :05:20:06:

✅!
for 1 hour 25 seconds
exp :01:00:25:
got :01:00:25:

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM