How to get Yesterday’s Date in Python

Introduction

Have you ever needed to get yesterday’s date in Python? If so, you might have found yourself wondering how to accomplish this. In this blog post, we will discuss how to get yesterday’s date using Python.

Knowing how to get yesterday’s date can be important in many situations. For example, if you are working with time-sensitive data and need to retrieve data from the previous day, or if you need to schedule recurring tasks that should run based on the previous day’s date. Whatever the reason may be, understanding how to get yesterday’s date is a useful skill for any Python programmer.

Let’s dive into how to get yesterday’s date with some examples!

Using datetime module

To get yesterday’s date in Python, we can use the `datetime` module. Here’s how to do it:

First, we need to import the `datetime` module using the `import` statement:


import datetime

Next, we need to create a `date` object for today’s date using the `today()` method of the `date` class:


today = datetime.date.today()

Now that we have today’s date, we can subtract one day from it to get yesterday’s date using the `timedelta` function:


one_day = datetime.timedelta(days=1)
yesterday = today - one_day

Finally, we can format yesterday’s date as a string using the `strftime()` method of the `date` class:


yesterday_str = yesterday.strftime('%Y-%m-%d')

This will give us yesterday’s date in the format `YYYY-MM-DD`. Of course, you can use a different format string if you prefer a different format.

Using timedelta object

To get yesterday’s date in Python, you can use the timedelta object from the datetime module. Here’s how:


import datetime

# create a timedelta object representing one day
one_day = datetime.timedelta(days=1)

# subtract one day from today's date using the timedelta object
yesterday = datetime.date.today() - one_day

# format yesterday's date as a string
yesterday_string = yesterday.strftime('%Y-%m-%d')

print(yesterday_string) # output: 2022-10-20

In the code above, we first import the datetime module. We then create a timedelta object called `one_day` by passing `days=1` as an argument. This represents one day.

Next, we subtract `one_day` from today’s date using the `-` operator. This gives us yesterday’s date, which we store in the variable `yesterday`.

Finally, we format `yesterday` as a string using the `strftime()` method and the `%Y-%m-%d` format string. This gives us a string in the format “YYYY-MM-DD”, which is a commonly used date format.

By using the timedelta object and simple arithmetic, we can easily get yesterday’s date in Python.

Conclusion

In conclusion, getting yesterday’s date in Python is a simple task that can be accomplished using the datetime module. We first import the module and then use the timedelta function to subtract a day from today’s date. The resulting date object can be formatted into a string using strftime function with the desired format.

It is important to note that the datetime module provides a lot of flexibility in working with dates and times in Python. We can perform various operations on dates, such as addition, subtraction, comparison, and formatting. Additionally, we can use the module to work with time zones and perform calculations with dates and times across different time zones.

In summary, knowing how to get yesterday’s date in Python is a useful skill that can come in handy when working with dates and times in applications. The datetime module provides a powerful set of tools for working with dates and times, making it an essential tool for any Python programmer.
Interested in learning more? Check out our Introduction to Python course!


How to Become a Data Scientist PDF

Your FREE Guide to Become a Data Scientist

Discover the path to becoming a data scientist with our comprehensive FREE guide! Unlock your potential in this in-demand field and access valuable resources to kickstart your journey.

Don’t wait, download now and transform your career!


Pierian Training
Pierian Training
Pierian Training is a leading provider of high-quality technology training, with a focus on data science and cloud computing. Pierian Training offers live instructor-led training, self-paced online video courses, and private group and cohort training programs to support enterprises looking to upskill their employees.

You May Also Like

Data Science, Tutorials

Guide to NLTK – Natural Language Toolkit for Python

Introduction Natural Language Processing (NLP) lies at the heart of countless applications we use every day, from voice assistants to spam filters and machine translation. It allows machines to understand, interpret, and generate human language, bridging the gap between humans and computers. Within the vast landscape of NLP tools and techniques, the Natural Language Toolkit […]

Machine Learning, Tutorials

GridSearchCV with Scikit-Learn and Python

Introduction In the world of machine learning, finding the optimal set of hyperparameters for a model can significantly impact its performance and accuracy. However, searching through all possible combinations manually can be an incredibly time-consuming and error-prone process. This is where GridSearchCV, a powerful tool provided by Scikit-Learn library in Python, comes to the rescue. […]

Python Basics, Tutorials

Plotting Time Series in Python: A Complete Guide

Introduction Time series data is a type of data that is collected over time at regular intervals. It can be used to analyze trends, patterns, and behaviors over time. In order to effectively analyze time series data, it is important to visualize it in a way that is easy to understand. This is where plotting […]