How to get yesterday’s datetime in Python and Pandas?

Get yesterday datetime in Python

You can get the previous day datetime value in python by following this short procedure:

  • Use 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.timedelta(days=1)

Datetime to string in python

The code that we posted above returns a datetime object:


This will return

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:


Here’s our data, note the new column that has the calculated yesterday dates:


Next learning

How to calculate time differences in Python 3 programs?