How To Yesterday Date In Python

In this blog post, we will learn how to get yesterday’s date using Python. Python’s built-in datetime module provides various functions and classes for working with dates and times. We will use the datetime class and its methods to get yesterday’s date.

Getting Yesterday’s Date

To get yesterday’s date, we will first import the datetime module, which provides the datetime class. We will then use the date.today() method to get the current date and subtract one day using the timedelta function. Here’s how you can do it:

from datetime import datetime, timedelta

today = datetime.today()
yesterday = today – timedelta(days=1)

print(yesterday)

The code above will output yesterday’s date, including the time, looking like this:

    2021-10-04 15:29:31.123456
    

Formatting the Output

If you want to display only the date part without the time, you can use the date() method. Here’s an example:

from datetime import datetime, timedelta

today = datetime.today()
yesterday = today – timedelta(days=1)

print(yesterday.date())

The output will now look like this:

    2021-10-04
    

If you want to display the date in a different format, you can use the strftime() method. This method allows you to format the date using format codes. For example, if you want to display the date in the format “DD-MM-YYYY”, you can use the following code:

from datetime import datetime, timedelta

today = datetime.today()
yesterday = today – timedelta(days=1)

formatted_date = yesterday.strftime(‘%d-%m-%Y’)
print(formatted_date)

The output will now look like this:

    04-10-2021
    

For more information on the available format codes, you can refer to the Python official documentation.

Conclusion

In this blog post, we have learned how to get yesterday’s date using Python’s built-in datetime module. We have also learned how to format the date to display it in different formats. This can be useful in various applications, such as log analysis, data processing, and report generation.