1

I have the date object which is as follows. Date: 2025-11-30. If I add 3 month to it using following code, it will raise an Exception as follows.

code:

def get_next_n_month_forward(date, n):
    if date.month + n > 12:
        next_month = date.replace(year=date.year + 1,
                                  month=(date.month + n) % 12)
    else:
        next_month = date.replace(month=(date.month + n))
    return next_month

exception:

ValueError: day is out of range for month

As far as I can understand from error it is because february does not have 30th day.

Question: How can I make it set to the last day of the month? !Note: In my case it would be 29th or 28th of February.

Madiyor
  • 761
  • 9
  • 23

1 Answers1

1

You can use timedelta object to increase and decrease dates

from datetime import timedelta
import datetime
d = datetime.datetime.today()
new_d = d + timedelta(days=1)

In order to set the date to the last day of month, you can set the date to the 1st of the next month and then decrease it by 1 day:

from datetime import timedelta
import datetime
day = datetime.datetime.today()
prev_month_last_day = day.replace(day=1) - timedelta(days=1)
Pavel Botsman
  • 773
  • 1
  • 11
  • 25