How to Subtract Year to Date in Python?

By Hardik Savani October 30, 2023 Category : Python

This example is focused on python subtract years to date example. We will look at example of how to subtract years to date in python. you will learn how to subtract year to current date in python. you will learn python minus years to date in dataframe. You just need to some step to done 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.

You can use these examples with python3 (Python 3) version.

Example 1: Python Subtract Years to Date

main.py

from datetime import datetime
from dateutil.relativedelta import relativedelta
  
myDateString = "2022-06-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-06-01 00:00:00
New Date :
2020-06-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-06-15 09:30:01.236313
New Date :
2020-06-15 09:30:01.236313

I hope it can help you...

Tags :
Shares