Python Subtract Years to Date Example

Published On: 07/09/2022 | Category: Python


Hi Guys,

This is a short guide on python 3 subtract years to date string. I would like to show you python subtract years to date example. This post will give you simple example of how to subtract years to date in python. I would like to show you python minus years to date in dataframe. you will do the following things for python subtract 1 year to date string.

In this example, I will give two examples for you of how to subtract years to date in python and how to subtract years to today's date in python. therefore, let's see below example code and try it.

So let's see bellow example:

Example 1: Python Subtract Years to Date main.py
from datetime import datetime
from dateutil.relativedelta import relativedelta
  
myDateString = "2022-09-01"
  
myDate = datetime.strptime(myDateString, "%Y-%m-%d")
  
subYearNumber = 2;
newDate = myDate - relativedelta(years=subYearNumber)
  
print("Old Date :")
print(myDate)
  
print("New Date :")
print(newDate)
Output:
Old Date :
2022-09-01 00:00:00
New Date :
2020-09-01 00:00:00
Example 2: Python Subtract Years to Current Date main.py
from datetime import datetime
from dateutil.relativedelta import relativedelta
  
myDate = datetime.today()
    
subYearNumber = 2;
newDate = myDate - relativedelta(years=subYearNumber)
 
print("Old Date :")
print(myDate)
  
print("New Date :")
print(newDate)
Output:
Old Date :
2022-09-07 04:35:47.312486
New Date :
2020-09-07 04:35:47.312486

It will help you....

Happy Coding!