In this article let’s learn how to add months to a datetime object in python.
Example 1: Adding years to a datetime object using NumPy library.
In this example we use the NumPy library, to create a datetime object using the np.datetime64() method and then add months using timedelta using the np.timedelta64() method. A string of date format is passed in the np.datetime64() method and the required number of months is added using the np.timedelta64() method.
Python3
# import packages import numpy as np # adding months to a given date print ( 'old date is : ' + str (np.datetime64( '2022-04' ))) new_date = np.datetime64( '2022-04' ) + np.timedelta64( 5 , 'M' ) print ( 'new date is : ' + str (new_date)) |
Output:
old date is : 2022-04 new date is : 2022-09
Example 2: Adding years to a datetime object using relativedelta
In this example, we use datetime and dateutil packages. The current date is known by using the datetime.date() method is used to create a date object by specifying the year, month, and day, and by using the relativedelta() method we add the number of months, and finally, we get a new datetime object.
Python3
# import packages from datetime import date from dateutil.relativedelta import relativedelta # adding months to a particular date print ( 'date : ' + str (date( 2020 , 5 , 15 ))) new_date = date( 2020 , 5 , 15 ) + relativedelta(months = 5 ) print ( 'new date is : ' + str (new_date)) |
Output:
date : 2020-05-15 new date is : 2020-10-15
Example 3: Adding years to a datetime object using the panda’s library.
In this example, we import the pandas’ package. In pandas, a string is converted to a datetime object using the pd.to_datetime() method and pd.DateOffset() method is used to add months to the created pandas object. finally, a new datetime object is created.
Python3
# import packages import pandas as pd # adding months to a particular date present = '2022-05-05' print ( 'date : ' + present) new_date = pd.to_datetime(present) + pd.DateOffset(months = 5 ) print ( 'new date is : ' + str (new_date)) |
Output:
date : 2022-05-05 new date is : 2022-10-05 00:00:00