How to subtract days from date in Python

Today we are going to learn how to subtract days from date in Python. Here we will provide some examples so that we can learn day subtraction from a date in Python.

So In this Python tutorial, we gonna learn the following things:

  • Subtract days from a specific date
  • Subtract days from the current date

Subtract days from a date in Python

To subtract days from a date we will use datetime module.

From this module we will import the following classes:

  1. datetime
  2. timedelta
from datetime import datetime, timedelta

Subtract days from the current date in Python

The below program will subtract any specific days from current date

from datetime import datetime, timedelta
current_date = datetime.now()
new_date = current_date - timedelta(days=52)
print (new_date)

Output:

$ python codespeedy.py
2019-02-10 23:39:28.749808

We can also use datetime.today() instead of datetime.now() both will give you the same output.



Both of them will return the current date time. ( Local or system date )

timedelta object can be basically used to work with time. It helps us to represent the time duration. On the above program, you can see we used timedelta(days=52) that means it will represent a time of days 52.

current_date is a variable to store the current date time. Using “-” operator we have subtracted 52 days from current_date.

Subtract days from a specific date

To subtract days from a particular date, we can use the below program,

from datetime import datetime, timedelta
particular_date = datetime(2019, 3, 6)
new_date = particular_date - timedelta(days=52)
print (new_date)

Output:

$ python codespeedy.py
2019-01-13 00:00:00

Learn more,

Leave a Reply

Your email address will not be published. Required fields are marked *