How to increment datetime by custom months in python without using library


Question

I need to increment the month of a datetime value

next_month = datetime.datetime(mydate.year, mydate.month+1, 1)

when the month is 12, it becomes 13 and raises error "month must be in 1..12". (I expected the year would increment)

I wanted to use timedelta, but it doesn't take month argument. There is relativedelta python package, but i don't want to install it just only for this. Also there is a solution using strtotime.

time = strtotime(str(mydate));
next_month = date("Y-m-d", strtotime("+1 month", time));

I don't want to convert from datetime to str then to time, and then to datetime; therefore, it's still a library too

Does anyone have any good and simple solution just like using timedelta?

1
181
8/20/2015 2:01:41 AM

Accepted Answer

Edit - based on your comment of dates being needed to be rounded down if there are fewer days in the next month, here is a solution:

import datetime
import calendar

def add_months(sourcedate, months):
    month = sourcedate.month - 1 + months
    year = sourcedate.year + month // 12
    month = month % 12 + 1
    day = min(sourcedate.day, calendar.monthrange(year,month)[1])
    return datetime.date(year, month, day)

In use:

>>> somedate = datetime.date.today()
>>> somedate
datetime.date(2010, 11, 9)
>>> add_months(somedate,1)
datetime.date(2010, 12, 9)
>>> add_months(somedate,23)
datetime.date(2012, 10, 9)
>>> otherdate = datetime.date(2010,10,31)
>>> add_months(otherdate,1)
datetime.date(2010, 11, 30)

Also, if you're not worried about hours, minutes and seconds you could use date rather than datetime. If you are worried about hours, minutes and seconds you need to modify my code to use datetime and copy hours, minutes and seconds from the source to the result.

119
3/15/2019 7:46:12 PM

This is short and sweet method to add a month to a date using dateutil's relativedelta.

from datetime import datetime
from dateutil.relativedelta import relativedelta

date_after_month = datetime.today()+ relativedelta(months=1)
print 'Today: ',datetime.today().strftime('%d/%m/%Y')
print 'After Month:', date_after_month.strftime('%d/%m/%Y')

Output:

Today: 01/03/2013

After Month: 01/04/2013

A word of warning: relativedelta(months=1) and relativedelta(month=1) have different meanings. Passing month=1 will replace the month in original date to January whereas passing months=1 will add one month to original date.

Note: this will requires python-dateutil. To install it you need to run in Linux terminal.

sudo apt-get update && sudo apt-get install python-dateutil

Explanation : Add month value in python


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon