[英]Python time in format => [days:hours:minutes:seconds] to seconds
I have this function that tranforms for example 我有例如转换的此功能
timeToSeconds("1:12:45:66.6")
>>>132366.6
But I admit it don't follow the DRY concept, check it out: 但我承认它不遵循DRY概念,请检查一下:
def timeToSeconds(time):
t = time.split(':')
try:
if len(t) == 1:
try:
type(eval(t[0])) in [int, float]
except:
return False
return eval(time)
elif len(t) == 2:
return float(t[-1]) + float(t[-2]) * 60
elif len(t) == 3:
return float(t[-1]) + float(t[-2]) * 60 + float(t[-3]) * 3600
elif len(t) == 4:
return float(t[-1]) + float(t[-2]) * 60 + float(t[-3]) * 3600 + float(t[-4]) * 86400
else:
return False
except:
return False
How would be a better way to write it? 怎么会有更好的书写方式? Note that is return False when input contains characters.
请注意,当输入包含字符时,返回False。
Don't return False
to indicate an error. 不要返回
False
来指示错误。 False == 0.0
in Python. False == 0.0
在Python中。 0.0
is a valid result for "0:0:0:0.0"
. 0.0
是"0:0:0:0.0"
的有效结果。 You could allow exceptions to propagate instead: 您可以允许例外传播:
def to_sec(timedelta_string, factors=(1, 60, 3600, 86400)):
"""[[[days:]hours:]minutes:]seconds -> seconds"""
return sum(x*y for x, y in zip(map(float, timedelta_string.split(':')[::-1]), factors))
Or if you need to suppress exceptions then return None
: 或者,如果您需要抑制异常,则返回
None
:
def timeToSeconds(time, default=None):
try:
return to_sec(time)
except ValueError:
return default
def timeToSeconds(time):
multi = [1,60,3600,86400]
try:
time = map(float,time.split(":"))
t_ret = 0
for i,t in enumerate(reversed(time)):
t_ret += multi[i] * t
return t_ret
except ValueError:
return None
print timeToSeconds("1:12:45:66.6")
print timeToSeconds("12:45:66.6")
print timeToSeconds("45:66.6")
print timeToSeconds("66.6")
print timeToSeconds("c")
Output: 输出:
132366.6
45966.6
2766.6
66.6
None
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.