这是清单:
lsty = ['1:07:11', '2:37:28', '07:11', '1:07:11']
时间可以是'2:37:28'(2小时37分28秒)或'07:11'(7分11秒)。我如何总结清单?
答案 0 :(得分:1)
您可能会发现本机python datetime.timedelta
对象很有用,它允许您以Python理解的方式表示时间,并使用其他timedelta对象执行算术。
也许是这样的?这完全未经测试:
from datetime import timedelta
def sum_times(times):
sum = timedelta(0)
for time in times:
time_split = time.split(':') # Extract just time vals
if len(time_split) == 2: # Just mins/secs
t_delt = timedelta(minutes=time_split[0],
seconds=time_split[1])
else:
t_delt = timedelta(hours=time_split[0],
minutes=time_split[1],
seconds=time_split[2])
sum += t_delt # This is where the magic happens
return '%s:%s:%s' % (sum.hours, sum.minutes, sum.seconds)