python

Get yesterday date in python

In this post, you will learn how to get yesterday's date in python. We will be using date and timedelta from datetime python module to get it.

from datetime import date, timedelta

yesterday_date = date.today() - timedelta(1)

print(yesterday_date)

Here, we are importing date and timedelta from datetime module in python. We are following below steps to get yesterday's date using python.

1. Import date and timedelta form datetime module

2. Getting today's date using date.today() that will return the current date.

3. Getting time delta for the previous day using timedelta(days=1).

4. Subtracting time delta from today's date and this will return yesterday's date.

5. Printing yesterday's date.

from datetime import datetime, timedelta

yesterday_datetime = datetime.now() - timedelta(days=1)

yesterday_date = yesterday_datetime.strftime('%Y-%m-%d')

print(yesterday_date)
In the above code, we are using datetime from datetime module. We are getting current time and date using datetime.now() method and time delta using timedelta(days=1) method. After subtracting this time delta from current date and time we get yesterday's date with time. Now we are converting it to date only using strftime() function and passing the desired date format as a parameter.
Was this helpful?