1
0
Fork 0
forked from s3lph/matemat

Replaced yet a calendar function not available in Python 3.6

This commit is contained in:
s3lph 2018-11-03 21:27:17 +01:00
parent 726b4a9370
commit eaab46b728

View file

@ -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