Add Months to Date Using Python

      No Comments on Add Months to Date Using Python

Often there is a requirement to add, subtract or calculate the difference between dates using Python. We will run through some examples of how to find and generate dates moving forward and backward through time using the datetime module.

Here are some quick examples on how to pull specific values out of the datetime object using the current date.

from datetime import datetime, date

dateandtime = datetime.today()  ## todays date and time
justdate = date.today()  ## just the date only, no time 

print(dateandtime)  ## date, time and miliseconds
print(dateandtime.year) ## 4 digits
print(dateandtime.month) ## 2 digits
print(dateandtime.day) ## 2 digits
print(dateandtime.hour) ## 24 hour format
print(dateandtime.minute) ## minute 0-59

print(justdate)     ## only the date, no time
print(justdate.year) 
print(justdate.month) 
print(justdate.day)  

Add Months to Date using relativedelta

We can use a python module called relativedelata to add and subtract months to our date. IN this example we are adding 14 months to the “date” provided.

from datetime import date
from dateutil.relativedelta import relativedelta

now = date.today()
print(now + relativedelta(months=14))

Add Years to Date

from datetime import date
from dateutil.relativedelta import relativedelta

now = date.today()
future = now + relativedelta(years=5)
print(future)

Add Days to Date

from datetime import datetime, date

dateandtime = datetime.today()
print(dateandtime.day + 12)

justdate = date.today()
print(justdate.day + 21)

Add and Subtract Multiple Values

We can also use multiple values to be more specific.

from datetime import date
from dateutil.relativedelta import relativedelta

now = date.today()
future = now + relativedelta(days=3, weeks=6, hours=-3)

print(future)

Add Days To Date Using timedelta

Within the datetime module we can use the timedelta object to add and subtract time and dates.

justdate = date.today()

adddays32 = timedelta(days=32)
print(justdate + adddays32)  ## add 32 days
print(justdate + adddays32 + adddays32)  ## same delta, add 32 twice

Subtract Days From Date

With the same timedelta object we can apply a negative number to subtract days instead.

justdate = date.today()

subdays32 = timedelta(days=-32)
print(justdate + subdays32 + subdays32)  ## subtract 64 days
print(justdate + subdays32)  ## subtract 32 days

Adding and Subtracting multiple time values

The timedelta object allows us to apply changes to multiple time values in one object such as weeks, days and hours. Each parameter accepts positive and negative numbers.

dateandtime = datetime.today()  ## todays date and time

multivalue = timedelta(
weeks=1,
days=8,
seconds=-15,
minutes=33,
hours=-3)

print(dateandtime + multivalue)  
print(dateandtime + multivalue + multivalue)  ## apply the values twice