Back

Explore Courses Blog Tutorials Interview Questions
0 votes
1 view
in Python by (19.9k points)

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

1 Answer

0 votes
by (25.1k points)

Use this code:

from datetime import timedelta

def convert(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(“Output:”, convert(test))

Output:

image

Related questions

Welcome to Intellipaat Community. Get your technical queries answered by top developers!

28.4k questions

29.7k answers

500 comments

94.7k users

Browse Categories

...