;

How To Add or Subtract a Month from a Given Date to Get a Specific Date in Python


Tutorialsrack 01/04/2020 Python

In this article, we will learn how to add or subtract a month from a given date to get a specific date in python. In python, there is no built-in function to add or subtract a month from a given date to get a specific date. So here we see how to add or subtract a month from a given date to get a specific date using the standard Python library.

Here is the source code to add or subtract a month from a given date to get a specific date in python.

In this example, d represents a DateTime and x represents a Number of Months and the value of x can be positive(+) or negative(-).

Example
# Import Module
import datetime
import calendar

def addMonths(d, x):
    newday = d.day
    newmonth = (((d.month - 1) + x) % 12) + 1
    newyear  = d.year + (((d.month - 1) + x) // 12)
    if newday > calendar.mdays[newmonth]:
        newday = calendar.mdays[newmonth]
        if newyear % 4 == 0 and newmonth == 2:
            newday += 1
    return datetime.date(newyear, newmonth, newday)

print("\n Add N Months to a Specific Date: ", addMonths(datetime.datetime(2020,1,30),1))
# Add N Months to a Specific Date:  2020-02-29

print("\n Add N Months to a Specific Date: ", addMonths(datetime.datetime(2019,1,30),1))
# Add N Months to a Specific Date:  2019-02-28

print("\n Add N Months to a Specific Date: ", addMonths(datetime.datetime(2020,12,30),1))
# Add N Months to a Specific Date:  2021-01-30

print("\n Add N Months to a Specific Date: ", addMonths(datetime.datetime(2020,1,30),-1))
# Add N Months to a Specific Date:  2019-12-30

print("\n Add N Months to a Specific Date: ", addMonths(datetime.datetime(2020,2,29),-6))
# Add N Months to a Specific Date:  2019-08-29

print("\n Add N Months to a Specific Date: ", addMonths(datetime.datetime(2020,2,29),-16))
# Add N Months to a Specific Date:  2018-10-29

I hope this article will help you to understand how to add or subtract a month from a given date to get a specific date in python.

Share your valuable feedback, please post your comment at the bottom of this article. Thank you!


Related Posts



Comments

Recent Posts
Tags