How to get yesterday’s date in python?

Created at 09-Dec-2023 , By samar


To get yesterday’s date in python we have to import the datetime module, which is a pre-built module in python we don’t have to install it externally.  

To work with date in python, the datetime module provides us date class and timedelta class. We have to import these classes from the datetime module at the top of the python script. Now, we can use these classes to obtain yesterday's date by employing the today() method  on the date class to get today’s date and subtracting a number of days using timedelta (timedelta(days=1)) from today's date.

Here are the step-by-step instructions for obtaining yesterday's date using the date class and timedelta class in Python.

1. Create a python file like yesterday.py

2. Import date and timedelta classes

from datetime import date
from datetime import timedelta

3. Get today's date

today = date.today()

4. Subtract one day from today using timedelta

yesterday = today - timedelta(days = 1)

5. Run python yesterday.py command in your terminal

6. Here is the output

Yesterday was:  2023-12-08

Full python script

from datetime import date
from datetime import timedelta

today = date.today()
yesterday = today - timedelta(days = 1)

print("Yesterday was: ", yesterday)

 

If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.

Buy Me A Coffee

Don't forget to share this article! Help us spread the word by clicking the share button below.

We appreciate your support and are committed to providing you valuable and informative content.

We are thankful for your never ending support.