From eaab46b7286c9efeb613139939ea4f5d3f4665b8 Mon Sep 17 00:00:00 2001 From: s3lph Date: Sat, 3 Nov 2018 21:27:17 +0100 Subject: [PATCH] Replaced yet a calendar function not available in Python 3.6 --- matemat/util/monthdelta.py | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) 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