To subtract days from a datetime variable using Python, the easiest way is to use the Python timedelta() function from the datetime module.
from datetime import timedelta, datetime
now = datetime.now()
two_days_in_past = now - timedelta(days=2)
print(now)
print(two_days_in_past)
#Output:
2022-02-08 09:27:25.929000
2022-02-06 09:27:25.929000
When working with data in Python, many times we are working with dates. Being able to manipulate and change dates easily is very important for efficient processing.
One such change is to be able to subtract days from a date.
With Python, we can easily subtract days from a datetime variable with the help of the datetime module.
To subtract days from a datetime variable in Python, we can use the timedelta() function from the datetime module.
Below is code that shows you how to subtract days to get some datetimes in the past using Python.
from datetime import timedelta, datetime
now = datetime.now()
two_days_in_past = now - timedelta(days=2)
ten_days_in_past = now - timedelta(days=10)
one_hundred_days_in_past = now - timedelta(days=100)
print(now)
print(two_days_in_past)
print(ten_days_in_past)
print(one_hundred_days_in_past)
#Output:
2022-02-08 09:27:25.929000
2022-02-06 09:27:25.929000
2022-01-29 09:27:25.929000
2021-10-31 09:27:25.929000
You can also use date in the same way to subtract days from a date variable.
Below are some examples of subtract days from a date variables in Python.
from datetime import timedelta, date
two_days_in_past = date.today() - timedelta(days=2)
ten_days_in_past = date.today() - timedelta(days=10)
one_hundred_days_in_past = date.today() - timedelta(days=100)
print(date.today())
print(two_days_in_past)
print(ten_days_in_past)
print(one_hundred_days_in_past)
#Output:
2022-02-08
2022-02-06
2022-01-29
2021-10-31
If instead you’d like to add days to a date in Python, you can use a very similar method as shown above but add the timedelta() function.
Subtracting One Day to Get Yesterday’s Date Using Python
We can easily get yesterday’s date using the Python datetime module. To get yesterday’s date, we just need to subtract 1 day using the timedelta() function.
Below is the Python code which will allow you to get yesterday’s date.
from datetime import timedelta, date
yesterday_date = date.today() - timedelta(days=1)
print(date.today())
print(yesterday_date)
#Output:
2022-02-08
2022-02-07
How to Subtract Days from a Date With pandas in Python
If you are using the Python pandas module, we can subtract days to from a date easily.
With pandas, to subtract days to from a date, we use the DateOffset() function.
Below is an example of how to use pandas to subtract days to from a date in Python.
import pandas as pd
startdate = "01/29/2022"
enddate = pd.to_datetime(startdate) - pd.DateOffset(days=5)
print(startdate)
print(enddate)
#Output:
2022-01-29 00:00:00
2022-01-24 00:00:00
Hopefully this article has been beneficial for you to learn how to subtract days to from a date using Python.