一个函数,可以将用户的时间戳作为输入,并将其转换为总秒数



我一直在尝试编写一个脚本,接受用户的文本作为时间戳,将其转换为总秒数,然后启动计时器。例如

Time: 1h:1m:30s
>> 3690s

我已经想出了这个从用户获取时间戳的解决方案

def toSecond(timestring):
t = 0
remove_space = lambda str: str.replace(" ", "")
timestring = remove_space(timestring)
try:
if (":") in timestring:
time = timestring.split(":")
try:
for i in time:
if i[-1] in ("s", "S" "M", "m", "h", "H") and i[0].isnumeric():
if i[-1] in ("h", "H"):
t += int(i[:-1]) * 3600
elif i[-1] in ("m", "M"):
t += int(i[:-1]) * 60
else:
t += int(i[:-1])
else:
print("No num or no char Provided")
except IndexError:
print("nothing provided")
else:
if (
timestring[-1] in ("s", "S" "M", "m", "h", "H")
and timestring[0].isnumeric()
):
if timestring[-1] in ("h", "H"):
t += int(timestring[:-1]) * 3600
elif timestring[-1] in ("m", "M"):
t += int(timestring[:-1]) * 60
else:
t += int(timestring[:-1])
elif timestring.isnumeric():
t += int(timestring)
else:
print("No time Provided")
except ValueError:
print("Error Value")
return t

这个解决方案正在发挥作用,然而,我想知道如何才能更短、更高效地完成这项工作。

提取小时、分钟和秒,然后像这样使用datetime.timedelta

from datetime import timedelta
ts = "1h:1m:30s"
time_indicators = ["H", "h", "M", "m", "S", "s"]
for ind in time_indicators:
ts = ts.replace(ind, "")
hours, minutes, seconds = ts.split(":")
print(timedelta(hours=int(hours), minutes=int(minutes), seconds=int(seconds)).total_seconds())


如果您想使用split捕获错误的用户输入,则使用regex:

import re
UNIT_TO_SECONDS = {
'h': 3600,
'm': 60,
's': 1
}
def parse_part(part):
match = re.match(r'^(d+)([HhMmSs])$', part)
if match is None:
raise ValueError(f'"{part}" is not a valid part of time')
return (int(match.group(1)),match.group(2).lower() )
def to_seconds_part(part):
nb, unit = parse_part(part)
return nb * UNIT_TO_SECONDS[unit]

def to_seconds(user_input):
parts = user_input.split(':')
parts_seconds = list(map(to_seconds_part, parts))
return sum(parts_seconds)

最新更新