Add values โ€‹โ€‹02:12, 03:45 ... from the list together to make the time format = hours: minutes: seconds

I want to convert a string in a few minutes and then add it all and return it as a string. I'm having difficulty with this.

I have a list that contains this:

TimeL = ['02: 32 ',' 03:43 ',' 01:05 ',' 56:03 ']

I want to add these minutes: seconds together and return a value equal to the sum in the hours format: mm: ss, but if their value is not enough to make an hour, I just want to return a value that is mm: ss,

for now, all I can do is convert every thing into seconds and add them, but thatโ€™s not what I want, this is what I knew how to do.

def getTIME(s): l = s.split(":") return int(l[0])*(60) + int(l[1]) for i in range(len(TimeL)): NEW = getTIME(TimeL[i]) NewTotalTime = NewTotalTime + NEW 

so my method will return a value that will be only seconds .. since 3432 seconds. I want it to be hours: minutes: seconds, and I'm stuck. Anyone can help even a little, it would be great to thank you!

0
source share
2 answers

Use the following:

 str(datetime.timedelta(seconds=3432)) 

To do this, you need to import the datetime module. You already have the number of seconds, and this will convert it to a string with hours, minutes and seconds.

+1
source share

Is this what you want. 1 min = 60 seconds, so you divide the seconds by 60. Your problem is that you need to divide by 60.0 in python to get the exact value (float value). After that, you take the smallest integer value ( math.floor ), for example. 150 seconds is 2.5 minutes, so you take 2 minutes, 2 minutes - 120 seconds, you delete this value from 150 to 30. This is the remaining number of seconds. You apply the same reasoning for several hours (60 minutes)

 import sys import math def getSeconds(s): l = s.split(":") return int(l[0])*(60) + int(l[1]) def getTotalString(time_list): total_secs = 0 for time_str in time_list: total_secs += getSeconds(time_str) total_mins = total_secs/60.0 mins = math.floor(total_mins) secs = total_secs-mins*60 if mins<60: return '%.2d:%.2d' % (mins, secs) else: hours = math.floor(mins/60.0) mins = mins-60*hours return '%.2d:%.2d:%.2d' % (hours, mins, secs) if __name__ == '__main__': print getTotalString(sys.argv[1:]) 

The approach for calculating the sum of seconds can be performed on a single line in Python:

 total_secs = sum(getSeconds(time_str) for time_str in time_list) 

sum will calculate the sum of the numbers in the list (or iterator). You can provide it with a list of numbers or a generator of numbers to add, the number of seconds in each time string in the list

I hope I made this as clear and instructive as possible, but you can use a simpler solution to the datetime module.

UPDATE: This is Python 2.x, not Python 3. so it may not work as expected, but the idea is the same, the syntax is different.

+1
source share

All Articles