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

Question:

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)

Asked By: icn

||

Answers:

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
Answered By: Alex Martelli

Use dateutil module. It has relative time deltas:

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

Beautiful.

Answered By: nosklo
from calendar import mdays
from datetime import datetime, timedelta

today = datetime.now()
next_month_of_today = today + timedelta(mdays[today.month])

I don’t want to import dateutil. Have a try this. Good luck.

Answered By: zerone
import calendar, datetime

def next_month ( date ):
    """return a date one month in advance of 'date'. 
    If the next month has fewer days then the current date's month, this will return an
    early date in the following month."""
    return date + datetime.timedelta(days=calendar.monthrange(date.year,date.month)[1])
Answered By: Ch'marr
from datetime import timedelta
try:
    next_month = (x.replace(day=28) + timedelta(days=7)).replace(day=x.day)
except ValueError:  # assuming January 31 should return last day of February.
    next_month = (x + timedelta(days=31)).replace(day=1) - timedelta(days=1)
Answered By: Collin Anderson

This is how I solved it.

from datetime import date
try:
    (year, month) = divmod(date.today().month, 12)
    next_month = date.today().replace(year=date.today().year+year, month=month+1)
except ValueError:
    # This day does not exist in next month

You can skip the try/catch if you only want the first day in next month by setting replace(year=date.today().year+year, month=month, day=1). This will always be a valid date since we have caught the month overflow using divmod.

Answered By: Hans Kristian

This work for me

import datetime
import calendar


def next_month_date(d):
    _year = d.year+(d.month//12)
    _month =  1 if (d.month//12) else d.month + 1
    next_month_len = calendar.monthrange(_year,_month)[1]
    next_month = d
    if d.day > next_month_len:
        next_month = next_month.replace(day=next_month_len)
    next_month = next_month.replace(year=_year, month=_month)
    return next_month

usage:

d = datetime.datetime.today()
print next_month_date(d)
Answered By: Daoctor

I often need to need to keep the date as last in month when adding months. I try to add the amount of months to the day after and then remove one day again. If that fails I add one more day until success.

from datetime import timedelta

DAY = timedelta(1)

def add_months(d, months):
    "Add months to date and retain last day in month."
    d += DAY
    # calculate year diff and zero based month
    y, m = divmod(d.month + months - 1, 12)
    try:
        return d.replace(d.year + y, m + 1) - DAY
    except ValueError:
        # on fail return last day in month
        # can't fail on december so just adding one more month
        return d.replace(d.year + y, m + 2, 1) - DAY
Answered By: Jolbas

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.

Answered By: icoxfog417

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
Answered By: Tech Amit

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!

Answered By: Tiago Ferreira

This Code Works for me:

NextMonth = self.CurruntMonth.replace(day=15) + datetime.timedelta(days=30)
Answered By: THARINDU SATHSARA
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.