Python Subtract Months to Date Example

16-Aug-2022

.

Admin

Python Subtract Months to Date Example

Hi dev,

Now, let's see a tutorial of python subtract months-to-date example. this example will help you python subtract 10 month date string. I would like to show you the python subtract months to date example. In this article, we will implement a python minus 1 month.

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

Example 1: Python Subtract Months to Date


main.py

from datetime import datetime

from dateutil.relativedelta import relativedelta

myDateString = "2022-06-01"

myDate = datetime.strptime(myDateString, "%Y-%m-%d")

subMonthNumber = 2;

newDate = myDate - relativedelta(months=subMonthNumber)

print("Old Date :")

print(myDate)

print("New Date :")

print(newDate)

Output:

Old Date :

2022-06-01 00:00:00

New Date :

2022-04-01 00:00:00

Example 2: Python Subtract Months to Current Date

main.py

from datetime import datetime

from dateutil.relativedelta import relativedelta

myDate = datetime.today()

subMonthNumber = 2;

newDate = myDate - relativedelta(months=subMonthNumber)

print("Old Date :")

print(myDate)

print("New Date :")

print(newDate)

Output:

Old Date :

2022-06-14 09:36:05.825956

New Date :

2022-04-14 09:36:05.825956

I hope it can help you...

#Python