5 Best Ways to Find Yesterday’s, Today’s, and Tomorrow’s Date in Python

Rate this post

πŸ’‘ Problem Formulation: In Python, managing dates and calculating past or future dates from a current date is a common task. For example, you might need to know yesterday’s date to generate reports for that day, today’s date for logging current operations, and tomorrow’s date for scheduling future tasks. This article will guide you through the best methods to find yesterday’s, today’s, and tomorrow’s dates using Python, assuming a current input date.

Method 1: Using datetime module

The datetime module in Python provides classes for manipulating dates and times. By utilizing the datetime.date class and its method timedelta(), we can easily calculate the dates for yesterday, today, and tomorrow.

Here’s an example:

from datetime import datetime, timedelta

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

print("Yesterday: ", yesterday)
print("Today: ", today)
print("Tomorrow: ", tomorrow)

Output:

Yesterday:  2023-03-22
Today:      2023-03-23
Tomorrow:   2023-03-24

This code snippet creates a date object representing today’s date and then uses timedelta() to subtract or add one day to find yesterday’s and tomorrow’s date, respectively. The print() statements then output each of the dates.

Method 2: Using pandas Timestamp

If you’re working with time series data, pandas library provides a convenient way to manipulate dates. The Timestamp object can be used to find yesterday’s, today’s, and tomorrow’s date with a high level of flexibility.

Here’s an example:

import pandas as pd

today = pd.Timestamp('now').normalize()
yesterday = today - pd.Timedelta(days=1)
tomorrow = today + pd.Timedelta(days=1)

print("Yesterday:", yesterday)
print("Today:", today)
print("Tomorrow:", tomorrow)

Output:

Yesterday: 2023-03-22 00:00:00
Today:     2023-03-23 00:00:00
Tomorrow:  2023-03-24 00:00:00

The code uses pandas to create a normalized Timestamp object for today’s date and then adds or subtracts a Timedelta object of one day to compute yesterday’s and tomorrow’s dates, respectively. It outputs these dates with timestamps set at the beginning of the day.

Method 3: Using dateutil module

The dateutil module provides powerful extensions to the standard datetime module. It is particularly useful for dealing with relative deltas which allow for the computation of different time units apart from a given date.

Here’s an example:

from datetime import datetime
from dateutil.relativedelta import relativedelta

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

print("Yesterday:", yesterday)
print("Today:", today)
print("Tomorrow:", tomorrow)

Output:

Yesterday: 2023-03-22
Today:     2023-03-23
Tomorrow:  2023-03-24

By importing relativedelta from the dateutil module, we can conveniently subtract or add days to the current date to find yesterday and tomorrow, respectively. This method is particularly useful for dealing with more complex date manipulation.

Method 4: Using Arrow library

Arrow is a modern Python library that provides better functionality for dates, times, and timestamps compared to Python’s standard datetime library. Arrow is known for its user-friendliness and timezone-aware operations.

Here’s an example:

import arrow

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

print("Yesterday:", yesterday)
print("Today:", today)
print("Tomorrow:", tomorrow)

Output:

Yesterday: 2023-03-22
Today:     2023-03-23
Tomorrow:  2023-03-24

With Arrow’s shift() method, we can move forward or backward from the current date to get tomorrow or yesterday, respectively. Arrow’s shift() method is more intuitive and handles time shifts straightforwardly.

Bonus One-Liner Method 5: Using List Comprehension

A one-liner approach can be used to find yesterday, today, and tomorrow using list comprehension along with the datetime module. This method prioritizes brevity and elegance.

Here’s an example:

from datetime import datetime, timedelta

dates = [(datetime.now().date() + timedelta(days=delta)).strftime('%Y-%m-%d') for delta in (-1, 0, 1)]
print("Yesterday, Today, Tomorrow:", dates)

Output:

Yesterday, Today, Tomorrow: ['2023-03-22', '2023-03-23', '2023-03-24']

Using list comprehension, this one-liner generates a list with formatted date strings for yesterday, today, and tomorrow. This method is clean and compact, creating a list in a single line of code.

Summary/Discussion

  • Method 1: datetime module. Strengths: Comes with Python’s standard library, easy to understand. Weaknesses: Basic functionality, may require additional modules for more intricate operations.
  • Method 2: pandas Timestamp. Strengths: Great for time series data, convenient for data analysis tasks. Weaknesses: Requires an external library, might be overkill for simple date operations.
  • Method 3: dateutil module. Strengths: Offers more control for complex date calculations. Weaknesses: Requires an additional module, could be too feature-rich for straightforward tasks.
  • Method 4: Arrow library. Strengths: User-friendly API, timezone-aware. Weaknesses: An external library that’s not included with Python by default.
  • Method 5: One-liner using list comprehension. Strengths: Elegant and concise. Weaknesses: Can be harder for beginners to understand and debug.