To get yesterday’s date in Python, the easiest way is to use the Python timedelta() function from the datetime module.
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
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 get yesterday’s date from today’s date.
With Python, we can easily get yesterday’s date from the current date with the help of the datetime module.
To get yesterday’s date, we need to subtract 1 day from today’s date in Python. To do so, we can use the timedelta() function from the datetime module.
Below is code that shows you how to subtract 1 day from today’s date to get yesterday’s date in Python.
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
Adding One Day to Get Tomorrow’s Date Using Python
We can easily get tomorrow’s date using the Python datetime module. To get tomorrow’s date, we just need to add 1 day using the timedelta() function.
Below is the Python code which will allow you to get tomorrow’s date.
from datetime import timedelta, date
tomorrow_date = date.today() + timedelta(days=1)
print(date.today())
print(tomorrow_date)
#Output:
2022-02-08
2022-02-09
How to Get Yesterday’s Date With pandas in Python
If you are using the Python pandas module, we can get the date of yesterday 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 get yesterday’s date in Python.
import pandas as pd
yesterday_date = pd.datetime.now() - pd.DateOffset(days=1)
Hopefully this article has been beneficial for you to learn how to get yesterday’s date using Python.