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.

4
  • using calendar module, stackoverflow.com/questions/42950/… Commented Jun 1, 2020 at 7:48
  • why not use relativedelta? Commented Jun 1, 2020 at 7:48
  • So what is result for 2020-01-31 + 1month ? what do you expectd ? Same day x month later, x*30 days later ? Commented Jun 1, 2020 at 7:49
  • did not really get about that, can you try anything I would take an example from your suggestions Commented Jun 1, 2020 at 7:52

1 Answer 1

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.