relativedelta(months=12)
is actually relativedelta(years=+1)
It automatically converts months to years. For example months=13
would result in relativedelta(years=+1, months=+1)
Further, years only change when months go below -11 or above 11. So if the amount of months
after the operation is still between -11 and 11, the year will not change.
The solution would be that you need to look at both the rdelta.years
and rdelta.months
values to get the "net months" you're looking for.
def total_months(rdelta):
return (rdelta.years * 12) + rdelta.months
You could subclass relativedelta
to make this a bit more intuitive for your use.
class reldelta(relativedelta):
@property
def total_months(self):
return (self.years * 12) + self.months
Then
>>> delta = reldelta(years=1) - relativedelta(months=4)
>>> delta
reldelta(years=+1, months=-4)
>>> delta.total_months
8
Of course, this can get messy if you want to try to factor in days to this, because the number of days in a month changes. This is why days
are not bounded like months are
>>> relativedelta(days=9999)
relativedelta(days=+9999)