Monday, November 18, 2024
Google search engine
HomeLanguagesAdd Years to datetime Object in Python

Add Years to datetime Object in Python

In this article let’s learn how to add years to a datetime object in python. 

Python Datetime module supplies classes datetime. These classes provide us with a number of functions to deal with dates, times, and time intervals. Date and datetime are an object in Python, so when you manipulate them, you are actually manipulating objects and not string or timestampsIf, there are multiple ways to do it. let’s demonstrate a few examples to understand.

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 years using timedelta using the np.timedelta64() method. a string of date format is passed in the np.datetime64() method and the required number of years is added using the np.timedelta64() method.

Python3




# import packages
import numpy as np
  
# adding years to a given date
print('old date is : '+ str(np.datetime64('2022')))
new_date = np.datetime64('2022')+ np.timedelta64(5,'Y')
print('new date is : '+str(new_date))


Output:

old date is : 2022
new date is : 2027

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 to create a date object by specifying the year, month, and day, and by using the relative delta() method we add the number of years. finally, a new datetime object is created.

Python3




# import packages
from datetime import date
from dateutil.relativedelta import relativedelta
  
# adding years to a particular date
print('date : '+ str(date(2020,5,15)))
new_date = date(2020,5,15) + relativedelta(years=5)
print('new date is : '+str(new_date))


Output:

present date : 2020-05-15
new date is : 2025-05-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. pd.DateOffset() method is used to add years to the created pandas object. finally, a new datetime object is created.

Python3




# import packages
import pandas as pd
  
# adding years to a particular date
present =  '2022-05-05'
print('date : '+ present )
new_date = pd.to_datetime(present)+pd.DateOffset(years= 5)
print('new date is : '+str(new_date))


Output:

date : 2022-05-05
new date is : 2027-05-05 00:00:00

RELATED ARTICLES

Most Popular

Recent Comments