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.
jadkik94
source share