![](/img/trans.png)
[英]How can I convert a string like 3hours26minutes33seconds into HH:MM:SS format in python?
[英]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.