Search code snippets, questions, articles...

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 = - timedelta(1)


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

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

In the above code, we are using datetime from datetime module. We are getting current time and date using 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?
Programming Feeds
Learn something new everyday on Devsheet