diff --git a/matemat/util/monthdelta.py b/matemat/util/monthdelta.py index 78cbd28..b93e2ab 100644 --- a/matemat/util/monthdelta.py +++ b/matemat/util/monthdelta.py @@ -21,9 +21,12 @@ def add_months(d: datetime, months: int) -> datetime: # Iterate the months between the passed date and the target month for i in range(months): days += calendar.monthrange(*nextmonth)[1] - nextmonth = calendar.nextmonth(*nextmonth) + if nextmonth[1] == 12: + nextmonth = nextmonth[0] + 1, 1 + else: + nextmonth = nextmonth[0], nextmonth[1] + 1 # Set the day of month temporarily to 1, then add the day offset to reach the 1st of the target month newdate: datetime = d.replace(day=1) + timedelta(days=days) # Re-set the day of month to the intended value, but capped by the max. day in the target month - newdate = newdate.replace(day=min(d.day, calendar.monthlen(newdate.year, newdate.month))) + newdate = newdate.replace(day=min(d.day, calendar.monthrange(newdate.year, newdate.month)[1])) return newdate