17-Aug-2022
.
Admin
Hi friends,
This simple article demonstrates of python subtract year-to-date example. you'll learn python to subtract years-to-date example. I’m going to show you python 3 subtract years from a date string. you can understand the concept of how to subtract years to date in python. Let's get started with python minus years to date in the data frame.
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 the 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...
#Python