Greetings to those that are still up!
I'm trying to sum up set elements:
HH:MM:SS
I can do that if the HH:MM:SS elements are in the list but fail if the elements are in the SET.
Here is what I got so far:
import datetime
add_time = ['00:00:15', '0:15:15', '5:15:15']
#add_time = set("00:00:15", "0:15:15", "5:15:15")
add_time = datetime.timedelta()
for i in add_time:
(h, m, s) = i.split(':')
d = datetime.timedelta(hours=int(h), minutes=int(m), seconds=int(s))
add_time += d
print(f" --- {str(add_time)}")[python]
[/python]
Any help is appreciated.
Thank you.
You can't create set as it's done on second line (outcommented).
>>> add_time = set("00:00:15", "0:15:15", "5:15:15")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: set expected at most 1 argument, got 3
>>> add_time = ['00:00:15', '0:15:15', '5:15:15']
>>> set(add_time) # you can convert existing list to set
{'00:00:15', '5:15:15', '0:15:15'}
>>> add_time = set(['00:00:15', '0:15:15', '5:15:15']) # you can provide list directly
>>> add_time
{'00:00:15', '5:15:15', '0:15:15'}
As for code itselt - I would write helper function to convert string to datetime object and then map this function to items in set and sum up. Something like:
from datetime import timedelta
add_time = {"00:00:15", "0:15:15", "5:15:15"}
def convert(time_str):
hrs, mins, secs = (int(unit) for unit in time_str.split(':'))
return timedelta(hours=hrs, minutes=mins, seconds=secs)
total = sum(map(convert, add_time), timedelta())
# total -> 5:30:45
Thank you!
You guys are great!
tster_V
Hope perfingo doesn't mind me infringing on his excellent function.
I was interested to see what happens when hour > 23 or time > 23:59:59
from datetime import timedelta
add_time = {"23:00:15", "6:15:15", "5:15:15"}
def convert(time_str):
hrs, mins, secs = (int(unit) for unit in time_str.split(':'))
return timedelta(hours=hrs, minutes=mins, seconds=secs)
total = sum(map(convert, add_time), timedelta())
minute = 60
hour = minute * 60
seconds = total.seconds
hours = divmod(seconds, hour)
minutes = divmod(hours[1], minute)
rem_seconds = minutes[1]
print(f'the total time is {hours[0]}:{minutes[0]}:{minutes[1]}')
Sure enough, looks like you won't get more than 23 hours!
It depends what you want. if one wants whole timedelta in seconds then
.total_seconds()
should be used instead of
.seconds
:
add_time_2 = {"23:00:15", "6:15:15", "5:15:15"}
total = sum(map(convert, add_time_2), timedelta())
print(total)
# output -> 1 day, 10:30:45
print(total.total_seconds())
# output -> 124245.0
time = total.total_seconds()
hours, reminder = divmod(int(time), 3600)
minutes, seconds = divmod(reminder, 60)
print(f'the total time is {hours}:{minutes}:{seconds}')
# output -> the total time is 34:30:45