Apr-05-2023, 08:52 PM
Did you read the sum documentation? I provided a link.
I try a test to see if it works. I'm going to make a list of timedelta objects and sum them up.
The int is here:
To correct we need to provide a "start" argument that is a timedelta object. We don't want the start to change the sum, so we want the timedelta equivalent of 0.
Quote:sum(iterable, /, start=0)
Sums start and the items of an iterable from left to right and returns the total. The iterable’s items are normally numbers, and the start value is not allowed to be a string.
I try a test to see if it works. I'm going to make a list of timedelta objects and sum them up.
from datetime import timedelta deltas = [timedelta(hours=1, minutes=59, seconds=59) for _ in range(10)] print(sum(deltas))
Error:Traceback (most recent call last):
File "...test.py", line 5, in <module>
print(sum(deltas))
TypeError: unsupported operand type(s) for +: 'int' and 'datetime.timedelta'
Does this mean I cannot use sum() with timedelta objects? A closer look at the error message reveals the problem.Quote:Unsupported types for +: int and timedelta.I see the timedelta objects, but where is the int?
The int is here:
Quote:sum(iterable, /, start=0)The result of sum is "start" and items from the iterable. I did not provide a "start" argument, so it uses the default value: 0. 0 is an int, and we cannot add an int and a timedelta object.
To correct we need to provide a "start" argument that is a timedelta object. We don't want the start to change the sum, so we want the timedelta equivalent of 0.
from datetime import timedelta deltas = [timedelta(hours=1, minutes=35, seconds=42) for _ in range(10)] print(sum(deltas, timedelta(seconds=0)))
Output:19:59:50
If we are from different worlds, they are the world of "Reading the documentation" and "Not reading the documentation". You need to hop on a rocket and travel to the world of "Reading the documentation". It can be difficult at first, but I think it results in a deeper understanding than looking for matching examples only. You'll like it. It is very nice.