how to get the same day of next month of a given day in python using datetime

Viewed 68750

i know using datetime.timedelta i can get the date of some days away form given date

daysafter = datetime.date.today() + datetime.timedelta(days=5)

but seems no datetime.timedelta(month=1)

12 Answers

Use dateutil module. It has relative time deltas:

import datetime
from dateutil import relativedelta
nextmonth = datetime.date.today() + relativedelta.relativedelta(months=1)

Beautiful.

Of course there isn't -- if today's January 31, what would be "the same day of the next month"?! Obviously there is no right solution, since February 31 does not exist, and the datetime module does not play at "guess what the user posing this impossible problem without a right solution thinks (wrongly) is the obvious solution";-).

I suggest:

try:
  nextmonthdate = x.replace(month=x.month+1)
except ValueError:
  if x.month == 12:
    nextmonthdate = x.replace(year=x.year+1, month=1)
  else:
    # next month is too short to have "same date"
    # pick your own heuristic, or re-raise the exception:
    raise

You can use calendar.nextmonth (from Python 3.7).

>>> import calendar
>>> calendar.nextmonth(year=2019, month=6)
(2019, 7)
>>> calendar.nextmonth(year=2019, month=12)
(2020, 1)

But be aware that this function isn't meant to be public API, it's used internally in calendar.Calendar.itermonthdays3() method. That's why it doesn't check the given month value:

>>> calendar.nextmonth(year=2019, month=60)
(2019, 61)

In Python 3.8 is already implemented as internal function.

This is how I solved it.

from datetime import datetime, timedelta
from calendar import monthrange

today_date = datetime.now().date()  # 2021-10-29
year = today_date.year
month = today_date.month

days_in_month = monthrange(year, month)[1]
next_month = today_date + timedelta(days=days_in_month)
print(next_month)  # 2021-11-29

Solution on Python3 without additional modules nor internal functions.

from datetime import date
today = date.today()
nextMonth = date(today.year+((today.month+1)//12) , ((today.month+1)%12), today.day)

Hurray for integer algebra!

This Code Works for me:

NextMonth = self.CurruntMonth.replace(day=15) + datetime.timedelta(days=30)
Related