0

This is the list:

lsty = ['1:07:11', '2:37:28', '07:11', '1:07:11']

Time can be like '2:37:28' (2h 37m 28s) or '07:11' (7m 11s). How can I sum up the list?

el323
  • 2,760
  • 10
  • 45
  • 80
  • Have you done any research at all? – Psytho Jan 05 '17 at 11:29
  • @Alex.S yes. I found this [link](http://stackoverflow.com/questions/2780897/python-sum-up-time). But it sums up when time is in this format h:m:s – el323 Jan 05 '17 at 11:32

1 Answers1

1

You may find the native python datetime.timedelta object useful, it allows you to represent time in a way that Python understands, and perform arithmetic with other timedelta objects.

Perhaps something like this? This is totally untested:

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)
David House
  • 121
  • 3