Get yesterday datetime in Python
You can get the previous day datetime value in python by following this short procedure:
- Use datetime.date.today() function to find the current date.
- Use the datetime.timedelta function to subtract one day from today’s.
Here’s the code that you can use to print the previous date value in Python:
yesterday = datetime.date.today() - datetime.timedelta(days=1)
Datetime to string in python
The code that we posted above returns a datetime object:
type(yesterday)
This will return datetime.date
We can easily change the format of the returned date using the strftime() function. Note that your datetime object will be converted to a string:
yes_str = yesterday.strftime('%d/%m/%y')
This will effectively return a string with format dd/mm/yy.
Getting yesterday date it yyyy-mm-dd format
As we learnt before, we are able to format our date in many ways. The following code converts our data object to a string with the ubiquitous ‘yyy-mm-dd’ format.
Calculate yesterday time in pandas
If you are using the 3rd party pandas Data Analysis library you might also need to calculate yesterday date and time from a timestamp.
Let’s start by importing the pandas library and initializing a very simple pandas DataFrame:
import pandas as pd
stamps = pd.Series(pd.date_range(start='5/1/24', periods = 5, freq ='B'))
revenue = [3298, 4617, 3094, 3032, 4393]
sales = pd.DataFrame( dict (sale_date = stamps, sales = revenue))
Next we will create a new column (series object) in our DataFrame use the DateOffset function and pass it a days=1 parameter to get the previous date.
sales['day_before'] = sales['sale_date'] - pd.tseries.offsets.DateOffset(days=1)
Let’s take a look at our DataFrame, using the head() method:
print(sales.head())
Here’s our data, note the new column that has the calculated yesterday dates:
sale_date | sales | day_before | |
---|---|---|---|
0 | 2024-05-01 | 3298 | 2024-04-30 |
1 | 2024-05-02 | 4617 | 2024-05-01 |
2 | 2024-05-03 | 3094 | 2024-05-02 |
3 | 2024-05-06 | 3032 | 2024-05-05 |
4 | 2024-05-07 | 4393 | 2024-05-06 |
FAQ
Can i use the pandas offset function to find yesterday’s date?
It is possible to use the pd.DateOffset function to subtract days:
yesterday_dt = datetime.date.today() - pd.DateOffset(days=1)
How to filter a DataFrame using yesterday date?
Use the loc accessor using a condition to filter rows where the date column matches yesterday.
yesterday_records = sales.loc[sales['sales_date'] == yesterday]