I have 3 lists, one for hours, one for minutes, and one for seconds. What I have done is create a function that will take 3 lists as input and calculate the total amount of time.
My issue is that the function is so redundant and my question to you, is simpy: what is a better way to do this.
Here is my function:
def final_time(hours,minutes,seconds):
draft_hours = sum(hours)
draft_minutes = sum(minutes)
draft_seconds = sum(seconds)
adding_seconds = str(draft_seconds/60.0)
second_converting = adding_seconds.split(".")
seconds_to_minutes = int(second_converting[0])
seconds_to_seconds = draft_seconds - (seconds_to_minutes * 60)
total_seconds = str(seconds_to_seconds)
more_minutes = draft_minutes + seconds_to_minutes
adding_minutes = str(more_minutes/60.0)
minute_converting = adding_minutes.split(".")
minutes_to_hours = int(minute_converting[0])
minutes_to_minutes = more_minutes - (minutes_to_hours * 60)
total_minutes = str(minutes_to_minutes)
total_hours = str(draft_hours + minutes_to_hours)
return total_hours + " hours, " + total_minutes + " minutes, and " + total_seconds + " seconds."
here is an example:
my_hours = [5, 17, 4, 8]
my_minutes = [40, 51, 5, 24]
my_seconds = [55, 31, 20, 33]
print final_time(my_hours,my_minutes,my_seconds)
above returns:
36 hours, 2 minutes, and 19 seconds.
so it does work, but as you can see, the function is just not a pythonic nor efficient function...what would a better method be?
s = sum(hours)*3600+sum(minutes)*60+sum(seconds)
return '%d hours %d minutes %d seconds'%( s/3600, (s%3600)/60, s%60)
I would probably convert it all to seconds first:
seconds = sum(3600*h + 60*m + s for (h,m,s) in zip(hours,minutes,seconds)
Now break it back down:
n_hours,minutes = divmod(seconds,3600)
n_minutes,n_seconds = divmod(minutes,60)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With