ItSolutionStuff.com

How to Subtract Months to Date in Python?

By Hardik Savani β€’ October 30, 2023
Python

This article will provide example of python subtract months to date example. I would like to share with you how to subtract months to date in python. In this article, we will implement a python minus 1 month. if you have question about python minus months from date then I will give simple example with solution. Alright, letÒ€ℒs dive into the steps.

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...

Tags: Python
Hardik Savani

Hardik Savani

I'm a full-stack developer, entrepreneur, and founder of ItSolutionStuff.com. Passionate about PHP, Laravel, JavaScript, and helping developers grow.

πŸ“Ί Subscribe on YouTube

We Are Recommending You

β˜…

How to Subtract Days from Date in Python?

Read Now β†’
β˜…

How to Add Days to Date in Python?

Read Now β†’
β˜…

Python Get Month Name from Number Example

Read Now β†’
β˜…

How to Get Tomorrow Date in Python?

Read Now β†’
β˜…

How to Get Current Time in Python?

Read Now β†’
β˜…

How to Get Current Month in Python?

Read Now β†’
β˜…

How to Get Current Day in Python?

Read Now β†’
β˜…

How to Get Current Year in Python?

Read Now β†’
β˜…

How to Get Current Date and Time in Python?

Read Now β†’
β˜…

How to Get Current Date in Python?

Read Now β†’