I have a list myList that contains relativedelta objects. I want to add all of these relativedeltas objects. I tried:
sum(myList)
but it gives TypeError.
TypeError: unsupported operand type(s) for : 'int' and 'relativedelta'
Even though relativedelta objects can be added with Opeartor
Code somehow:
from datetime import datetime
from dateutil.relativedelta import relativedelta
date1 = datetime(2018, 4, 9).date()
date2 = datetime(2019, 8, 18).date()
date3 = datetime(2014, 2, 1).date()
date4 = datetime(2018, 12, 30).date()
myList = []
rdelta1 = relativedelta(date2, date1)
myList.append(rdelta1)
rdelta2 = relativedelta(date4, date3)
myList.append(rdelta2)
print(sum(myList))
CodePudding user response:
This is because sum
uses start value as 0
.
>>> help(sum) Help on built-in function sum in module builtins: sum(iterable, /, start=0) Return the sum of a 'start' value (default: 0) plus an iterable of numbers When the iterable is empty, return the start value. This function is intended specifically for use with numeric values and may reject non-numeric types.
For example, sum([1, 2])
is 0 1 2
>>> sum([1, 2])
3
sum([1, 2], start=7)
is 7 1 2
>>> sum([1, 2], start=7)
10
So to solve this use one item(relativedelta
object) as start
argument and keep everything else in the iterable.
from datetime import datetime
from dateutil.relativedelta import relativedelta
date1 = datetime(2018, 4, 9).date()
date2 = datetime(2019, 8, 18).date()
date3 = datetime(2014, 2, 1).date()
date4 = datetime(2018, 12, 30).date()
myList = []
rdelta1 = relativedelta(date2, date1)
rdelta2 = relativedelta(date4, date3)
myList.append(rdelta2)
print(sum(myList, rdelta1)) # so both start and items in `MyList` are `relativedelta` types.
CodePudding user response:
Use reduce
from datetime import datetime
from dateutil.relativedelta import relativedelta
from functools import reduce
date1 = datetime(2018, 4, 9).date()
date2 = datetime(2019, 8, 18).date()
date3 = datetime(2014, 2, 1).date()
date4 = datetime(2018, 12, 30).date()
myList = []
rdelta1 = relativedelta(date2, date1)
myList.append(rdelta1)
rdelta2 = relativedelta(date4, date3)
myList.append(rdelta2)
print(reduce(lambda x, y: x y, myList))