How to get Yesterday’s Date in Python

Introduction:

Getting yesterday’s date is a common requirement in many Python applications. For example, you may need to generate a report that includes data from the previous day, or you may need to perform some data analysis on data collected yesterday. In such scenarios, it is essential to know how to get yesterday’s date in Python accurately.

Fortunately, Python provides built-in modules that make it easy to work with dates and times. In this section, we’ll explore how to use the datetime module to get yesterday’s date.

Using datetime module:

To get yesterday’s date in Python, we can use the datetime module. This module provides various classes to work with dates and times. The datetime class is particularly useful for working with dates.

Here’s an example of how to use the datetime module to get yesterday’s date:


import datetime

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

print("Yesterday was:", yesterday)

In this code, we first import the datetime module. Then, we use the `date.today()` method to get today’s date and store it in the `today` variable.

Next, we create a new variable called `yesterday` by subtracting one day from today using `datetime.timedelta(days=1)`. This creates a timedelta object representing a duration of one day, which we can subtract from today’s date to get yesterday’s date.

Finally, we print out yesterday’s date using the `print()` function.

This is a simple way to get yesterday’s date using Python’s built-in datetime module.

Using timedelta:

To get yesterday’s date in Python, you can use the timedelta method available in the datetime module. The timedelta method allows you to perform arithmetic operations on datetime objects.

First, you need to import the datetime module:


import datetime

Next, you can create a datetime object for today’s date using the now() method:


today = datetime.datetime.now()

Then, you can subtract one day from today’s date using the timedelta method:


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

The days parameter in the timedelta method specifies how many days to subtract from today’s date. In this case, we are subtracting one day.

Finally, you can print yesterday’s date using the strftime() method to format the output:


print(yesterday.strftime('%Y-%m-%d'))

The strftime() method formats the datetime object as a string. In this case, we are formatting it as ‘YYYY-MM-DD’. You can change the format string to display the date in a different format if desired.

Overall, using timedelta is a simple and effective way to get yesterday’s date in Python.

Using arrow module:

Python provides several modules for working with dates and times. One of the most popular is the arrow module, which offers a more intuitive and human-readable approach to working with dates and times.

To get yesterday’s date using arrow, we first need to install the module. This can be done via pip by running the following command:


pip install arrow

Once installed, we can import the module and use its `Arrow` class to create an object representing the current date and time. From there, we can simply subtract a day to get yesterday’s date:


import arrow

today = arrow.now()
yesterday = today.shift(days=-1).date()

print(yesterday)

In this example, we first create an `Arrow` object representing the current date and time using `arrow.now()`. We then use the `shift()` method to subtract one day from that date, resulting in an `Arrow` object representing yesterday’s date. Finally, we call the `date()` method on that object to get a Python `date` object representing yesterday’s date.

The output of this code will be something like:


2021-10-06

Overall, using the arrow module is a simple and effective way to work with dates and times in Python. Its intuitive syntax makes it easy to perform complex operations like getting yesterday’s date with just a few lines of code.

Conclusion:

To get yesterday’s date in Python, there are several ways to achieve this. One way is to use the `datetime` module which comes with Python’s standard library. Here is an example of how we can get yesterday’s date using the `datetime` module:


import datetime

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

print("Yesterday was:", yesterday)

In the code above, we first imported the `datetime` module. Then, we used the `date.today()` method to get today’s date and stored it in the `today` variable. Next, we used the `timedelta()` function to subtract one day from today’s date and stored it in the `yesterday` variable. Finally, we printed out yesterday’s date.

Another way to get yesterday’s date is by using the `dateutil` module. Here is an example of how to do that:


from dateutil.relativedelta import relativedelta
import datetime

today = datetime.date.today()
yesterday = today - relativedelta(days=1)

print("Yesterday was:", yesterday)

In the code above, we imported the `relativedelta` function from the `dateutil.relativedelta` module. Then, we used this function to subtract one day from today’s date and stored it in the `yesterday` variable.

Conclusion:
Both methods are effective in getting yesterday’s date in Python; however, if you need to perform more complex operations with dates, then using the `dateutil` module would be better suited for your needs. On the other hand, if you just need a simple way to get yesterday’s date without installing any additional packages, then using the `datetime` module would be a good choice.
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

Deep Learning, Tutorials

ChatGPT API Python Guide

Introduction Welcome to this tutorial on using the ChatGPT API from OpenAI with Python! ChatGPT is a state-of-the-art language model that can generate human-like responses to text-based inputs. With its ability to understand context and generate coherent responses, ChatGPT has become a popular tool for chatbots and conversational agents in a variety of industries. In […]

Python Basics, Tutorials

Using Min Function in Python

Introduction Python is a powerful programming language that can be used for a variety of tasks, including data analysis and manipulation. One common task in data analysis is finding the smallest number in a list, which one can do in a variety of ways, including using the Python min function. In this tutorial, we will […]

Python Basics, Tutorials

Understanding the Max Python Function

Introduction Lists are an important data structure in Python programming. They allow us to store a collection of values in a single variable. Sometimes we need to find the maximum value in a list, in this blog post we’ll cover how to use the max python function. This can be useful in many situations, for […]