【发布时间】:2022-01-23 00:19:57
【问题描述】:
我一直在尝试编写一个脚本,该脚本将接受来自用户的文本作为时间戳,将其转换为总秒数,然后启动一个计时器。例如
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
这个解决方案有效,但是,我想知道如何才能更短、更有效地做到这一点。
【问题讨论】:
标签: python python-3.x time timestamp