-1

i have an array filled with string which represent time elements and im trying to get the total time out of this array.


testArray=['02:30:57','15:09:18','01:00:18']
def arraysum(x): 
  if (len(x)%2==0):

     for i in range (0,len(x)-1,2):
            for j in range (1,len(x),2) :
                time2=datetime.strptime(x[i],"%H:%M:%S")
                time1=datetime.strptime(x[j],"%H:%M:%S")
                time1delta=timedelta(hours=time1.hour, minutes=time1.minute, seconds=time1.second)
                time2delta=timedelta(hours=time2.hour, minutes=time2.minute, seconds=time2.second)
                total=time2delta+time1delta
                print (total)


    else:
        for i in range (0,len(x),2):
            for j in range (1,len(x)-1,2) :
                time2=datetime.strptime(x[i],"%H:%M:%S")
                time1=datetime.strptime(x[j],"%H:%M:%S")
                time1delta=timedelta(hours=time1.hour, minutes=time1.minute, seconds=time1.second)
                time2delta=timedelta(hours=time2.hour, minutes=time2.minute, seconds=time2.second)
                total=time2delta+time1delta
                print (total)


arraysum(testArray)

this is the output i get which is incorrect. 17:40:15 16:09:36

I need it to show 18:40:15

user2241397
  • 69
  • 2
  • 11
  • 2
    Possible duplicate of [Python summing up time](https://stackoverflow.com/questions/2780897/python-summing-up-time) – Georgy Jul 05 '19 at 13:34

3 Answers3

2

Using datetime module. Using datetime.timedelta to increment time.

Ex:

import datetime

testArray=['02:30:57','15:09:18','01:00:18'] 
result = None
for d in testArray:
    if not result:
        result = datetime.datetime.strptime(d, "%H:%M:%S")
    else:
        value = datetime.datetime.strptime(d, "%H:%M:%S")
        result = result + datetime.timedelta(hours=value.hour, minutes=value.minute, seconds=value.second)

print(result.strftime("%H:%M:%S")) #-->18:40:33
Rakesh
  • 81,458
  • 17
  • 76
  • 113
1

Here is another way:

from datetime import timedelta


def f(t):
    result = timedelta()
    for i in t:
        hours, minutes, seconds = i.split(":")
        result += timedelta(
            hours=int(hours), minutes=int(minutes), seconds=int(seconds)
        )
    return result


test = ['02:30:57','15:09:18', '01:00:18']
print(f(test))
# result = 18:40:33
dildeolupbiten
  • 1,314
  • 1
  • 15
  • 27
0

If you're willing to use pandas the result becomes much easier as pandas comes with a lot of capability to parse stings into richer time objects.

import pandas as pd

testArray=['02:30:57','15:09:18','01:00:18']
total_time = sum((pd.Timedelta(t) for t in testArray), pd.Timedelta(0, 's'))

To print you have several options. str(total_time) returns '0 days 18:40:33', total_time.isoformat() returns 'P0DT18H40M33S', and repr(total_time) returns "Timedelta('0 days 18:40:33')".

If you don't want to use pandas, you can make a little helper function.

import datetime

testArray=['02:30:57','15:09:18','01:00:18']

def parse_timedelta_string(timedelta_string):
    hours, minutes, seconds = map(int, timedelta_string.split(':'))
    return datetime.timedelta(hours=hours, minutes=minutes, seconds=seconds)

total_time = sum((parse_timedelta_string(t) for t in testArray), datetime.timedelta(seconds=0))

print(total_time)
Kyle Parsons
  • 1,475
  • 6
  • 14