How to get yesterday's date in Python

Learn how to get yesterday's date in Python. Explore different methods, tips, real-world applications, and common error debugging.

Published on: 
Mon
Apr 6, 2026
Updated on: 
Wed
Apr 8, 2026
The Replit Team

To find yesterday's date in Python is a frequent task in data analysis and application development. Python’s datetime module offers simple, effective methods to handle this with just a few lines of code.

In this article, we'll cover several techniques to retrieve the previous day's date. You'll find practical tips, real-world applications, and common debugging advice to help you master date manipulation in your projects.

Using datetime.timedelta to get yesterday's date

from datetime import datetime, timedelta

yesterday = datetime.now() - timedelta(days=1)
print(yesterday.strftime('%Y-%m-%d'))--OUTPUT--2023-06-14

The most direct way to get yesterday's date involves date arithmetic. The timedelta object represents a duration of time. By creating a timedelta for one day, you can subtract it from the current moment.

The code first gets the current date and time using datetime.now(). Then, it subtracts a timedelta(days=1) object. This simple subtraction is powerful because it correctly handles all edge cases, like the transition from the first day of a month or year.

Basic date manipulation methods

While timedelta is powerful, you can gain more control by using the date object for simplicity, targeting specific times, and customizing the final output.

Using date object for simpler date handling

from datetime import date, timedelta

today = date.today()
yesterday = today - timedelta(days=1)
print(yesterday)--OUTPUT--2023-06-14

If you don't need the time component, using the date object is a cleaner approach. The date.today() method returns only the current date, which simplifies your code. You can then subtract a timedelta(days=1) just like before.

  • This method is more direct when you're only concerned with the calendar day.
  • Printing the result gives you the date in a standard format without needing strftime().

It’s a great way to keep your date arithmetic focused and readable.

Calculating yesterday at the start of the day

from datetime import datetime, timedelta

today_start = datetime.now().replace(hour=0, minute=0, second=0, microsecond=0)
yesterday_start = today_start - timedelta(days=1)
print(f"Yesterday at midnight: {yesterday_start}")--OUTPUT--Yesterday at midnight: 2023-06-14 00:00:00

For tasks like generating daily reports, you often need the exact start of yesterday. This method provides that precision by first establishing a clean timestamp for the beginning of today.

  • The replace() method is used on datetime.now() to create a new object with the time reset to midnight.
  • You achieve this by setting hour, minute, second, and microsecond to 0.
  • Subtracting a timedelta(days=1) from this "start of today" timestamp gives you the exact moment yesterday began.

Custom formatting for yesterday's date

from datetime import datetime, timedelta

yesterday = datetime.now() - timedelta(days=1)
formatted_date = yesterday.strftime('%A, %B %d, %Y')
print(formatted_date)--OUTPUT--Wednesday, June 14, 2023

Once you have yesterday's date, you'll often need to display it in a specific format. The strftime() method is perfect for this, letting you convert a datetime object into a custom string. It works by using special format codes that represent different parts of the date.

  • %A gives you the full weekday name, like "Wednesday".
  • %B provides the full month name, such as "June".
  • %d is the day of the month.
  • %Y represents the four-digit year.

You can combine these codes to create any date format you need.

Advanced date handling techniques

Beyond the standard library, you can also work with timestamps or leverage powerful libraries like arrow and pandas for more complex date handling needs.

Using timestamps to calculate yesterday

import time
from datetime import datetime

seconds_in_day = 86400 # 60 * 60 * 24
yesterday_timestamp = time.time() - seconds_in_day
yesterday = datetime.fromtimestamp(yesterday_timestamp)
print(yesterday.strftime('%Y-%m-%d'))--OUTPUT--2023-06-14

Working with timestamps offers a lower-level approach by operating directly with seconds. This method hinges on a simple calculation: subtracting the total number of seconds in a day from the current time.

  • You start by getting the current Unix timestamp—seconds since the epoch—with time.time().
  • Then, you subtract 86400 seconds to go back exactly one day.
  • Finally, the datetime.fromtimestamp() function converts this raw timestamp back into a familiar datetime object for formatting.

Using the arrow library for intuitive date handling

import arrow

now = arrow.now()
yesterday = now.shift(days=-1)
print(f"Yesterday: {yesterday.format('YYYY-MM-DD')}")
print(f"Yesterday in human terms: {yesterday.humanize()}")--OUTPUT--Yesterday: 2023-06-14
Yesterday in human terms: a day ago

The arrow library offers a more human-friendly approach to date manipulation, replacing complex arithmetic with intuitive methods. After getting the current time with arrow.now(), you can simply use shift(days=-1) to go back one day. This makes your code exceptionally readable.

  • The format() method is similar to strftime but uses its own syntax, like 'YYYY-MM-DD'.
  • A standout feature is humanize(), which converts the date into a relative, easy-to-read string like "a day ago".

Using pandas for date manipulation

import pandas as pd
from datetime import datetime

today = pd.Timestamp(datetime.now())
yesterday = today - pd.Timedelta(days=1)
print(f"Yesterday: {yesterday.strftime('%Y-%m-%d')}")
print(f"Is month end: {yesterday.is_month_end}")--OUTPUT--Yesterday: 2023-06-14
Is month end: False

For data-heavy tasks, pandas provides its own powerful date and time objects. The library uses pd.Timestamp and pd.Timedelta, which operate similarly to their standard library counterparts. You simply subtract a pd.Timedelta(days=1) from the current pd.Timestamp to get the previous day.

  • The real advantage comes from the rich set of built-in attributes that simplify data analysis.
  • For instance, you can instantly check if a date is the last day of the month using the convenient is_month_end property—a feature not available in the native datetime module.

Move faster with Replit

Replit is an AI-powered development platform that comes with all Python dependencies pre-installed, so you can skip setup and start coding instantly. This allows you to move from learning individual techniques, like using timedelta, to building complete applications with Agent 4.

Instead of piecing together code snippets, you can describe the app you want to build and the Agent will take it from an idea to a working product:

  • A daily report generator that automatically fetches data from the previous day and formats it for an email summary.
  • A simple task reminder that calculates due dates based on relative times like "yesterday" or "a week ago."
  • A data analysis utility that filters a sales log to show only transactions from yesterday and then calculates the daily total.

Simply describe your app, and Replit will write the code, test it, and fix issues automatically, all within your browser.

Common errors and challenges

Even simple date operations can have pitfalls; here are a few common errors to watch out for when working with dates in Python.

Handling timezone inconsistencies with datetime.now()

A frequent source of bugs is the naive nature of datetime.now(). It returns the current time based on your system's local settings, which can cause unexpected results if your application is used across different timezones.

  • For instance, "yesterday" for a user in New York might still be "today" for a server running in London.
  • Relying on the system's clock without context can lead to incorrect data filtering and reporting.

To avoid this, it's best practice to work with timezone-aware datetime objects, often by setting a universal timezone like UTC.

Using incorrect parameter names with timedelta

A simple typo can trip you up when using timedelta. The function expects its parameters to be plural, such as days=1 or weeks=2. If you accidentally use a singular form like timedelta(day=1), Python will raise a TypeError because it doesn't recognize the parameter. Always double-check that you're using the plural form to ensure your date arithmetic works as expected.

Comparing dates of different types

Python makes a distinction between "naive" and "aware" datetime objects. A naive object has no timezone information, while an aware object does. Trying to compare the two directly will result in a TypeError because Python can't logically compare a specific moment in time (aware) with an ambiguous one (naive). You must ensure both objects are of the same type—either both naive or both aware—before performing any comparisons.

Handling timezone inconsistencies with datetime.now()

The naive nature of datetime.now() creates subtle bugs when calculating elapsed time. If a Daylight Saving Time shift occurs during processing, the duration can be miscalculated by an hour. The code below shows a common pattern that is vulnerable to this issue.

from datetime import datetime

start_time = datetime.now()
# Some processing happens
end_time = datetime.now()
elapsed = end_time - start_time
print(f"Time elapsed: {elapsed}")

This simple subtraction, end_time - start_time, doesn't account for the clock jumping forward or backward during a Daylight Saving Time change, making your elapsed time incorrect. The following code demonstrates a more robust approach to avoid this issue.

from datetime import datetime
import pytz

timezone = pytz.timezone('UTC')
start_time = datetime.now(timezone)
# Some processing happens
end_time = datetime.now(timezone)
elapsed = end_time - start_time
print(f"Time elapsed: {elapsed}")

To fix this, you can use timezone-aware datetime objects. The pytz library lets you set a consistent timezone, like UTC, for both your start_time and end_time using datetime.now(timezone). This ensures the calculation end_time - start_time is accurate because it's based on a universal standard, not a local clock that might change. This is vital for logging systems or any application where precise time measurement is critical.

Using incorrect parameter names with timedelta

It's an easy mistake to make, but timedelta is particular about its argument names. A single letter can be the difference between success and a TypeError. The code below demonstrates what happens when you use the singular day instead of days.

from datetime import datetime, timedelta

today = datetime.now()
yesterday = today - timedelta(day=1)
print(yesterday.strftime('%Y-%m-%d'))

This code triggers a TypeError because the timedelta function is designed to only accept plural keyword arguments. The singular day=1 is an unrecognized parameter, causing the operation to fail. See the correct implementation below.

from datetime import datetime, timedelta

today = datetime.now()
yesterday = today - timedelta(days=1)
print(yesterday.strftime('%Y-%m-%d'))

The fix is to use the plural keyword argument days=1. Python’s timedelta function is strict and won't recognize singular forms like day, which is what causes the TypeError. This is a common slip-up, especially when coding quickly. Always double-check that you're using plural units—like days, hours, or weeks—for any time duration you define. This simple habit ensures your date arithmetic executes without a hitch.

Comparing dates of different types

It's a common pitfall to mix date types. Python will raise a TypeError if you try to compare a datetime object, which includes time, with a simpler date object. The two aren't directly compatible. The code below shows this error in action.

from datetime import datetime, date, timedelta

today_datetime = datetime.now()
yesterday_date = date.today() - timedelta(days=1)

if yesterday_date < today_datetime:
print("Yesterday is before today")

The comparison yesterday_date < today_datetime fails because one object holds only a date, while the other includes time, creating an ambiguity Python can't resolve. Check the code below for the correct way to handle this comparison.

from datetime import datetime, date, timedelta

today_datetime = datetime.now()
yesterday_date = date.today() - timedelta(days=1)

yesterday_datetime = datetime.combine(yesterday_date, datetime.min.time())
if yesterday_datetime < today_datetime:
print("Yesterday is before today")

To resolve this, you must convert one of the objects so they’re both the same type. The solution uses datetime.combine() to upgrade the date object into a full datetime object by adding a time component—in this case, midnight, using datetime.min.time(). With both variables as datetime objects, the comparison works correctly. Keep an eye out for this when mixing results from date.today() and datetime.now() in your code.

Real-world applications

Now that you know how to navigate the common pitfalls, you can apply these techniques to practical, real-world applications.

Using timedelta for date range analysis

A common application of timedelta is to establish a date range for analysis, such as filtering records that fall between yesterday and a week ago.

from datetime import datetime, timedelta

# Get yesterday's and last week's dates
today = datetime.now()
yesterday = today - timedelta(days=1)
last_week = today - timedelta(days=7)

# Check if an event date falls in a specific range
event_date = datetime.strptime("2023-06-12", "%Y-%m-%d")

if last_week <= event_date <= yesterday:
print(f"Event on {event_date.strftime('%Y-%m-%d')} happened in the past week")
else:
print(f"Event on {event_date.strftime('%Y-%m-%d')} is outside the past week range")

This snippet shows how to check if a date falls within a dynamic range. It calculates `yesterday` and `last_week` by subtracting `timedelta` objects from the current time. A separate `event_date` is then created from a string using `datetime.strptime()`.

  • The core logic lies in the chained comparison `last_week <= event_date <= yesterday`.
  • It’s a concise way to verify if `event_date` is chronologically between the two boundary dates, inclusive.

The boolean result of this check determines which message is printed.

Building a simple date-based activity logger

Date arithmetic is perfect for building a simple activity logger that automatically creates and accesses files based on the current or previous day.

from datetime import datetime, timedelta
import os

# Create file paths based on dates
today = datetime.now()
yesterday = today - timedelta(days=1)

log_dir = "logs"
today_log = os.path.join(log_dir, f"{today.strftime('%Y-%m-%d')}.log")
yesterday_log = os.path.join(log_dir, f"{yesterday.strftime('%Y-%m-%d')}.log")

# Simulate reading yesterday's log
print(f"Reading yesterday's log from: {yesterday_log}")

# Write a new entry to today's log
print(f"Writing to today's log at: {today_log}")

This code dynamically generates file paths for daily logs. It first calculates the dates for `today` and `yesterday` using `datetime.now()` and `timedelta(days=1)`. These date objects are then formatted into strings to be used in the filenames.

  • The `strftime('%Y-%m-%d')` method converts the dates into a standard `YYYY-MM-DD` format.
  • `os.path.join()` safely constructs the full file path, ensuring it works correctly on any operating system.

This approach is ideal for automating tasks like creating or accessing log files that are organized by date.

Get started with Replit

Now, turn your knowledge into a real tool. Tell Replit Agent to build "a dashboard that shows yesterday's user signups" or "a script that archives log files from the previous day."

The Agent writes the code, tests for errors, and deploys your application for you. Start building with Replit.

Get started free

Create and deploy websites, automations, internal tools, data pipelines and more in any programming language without setup, downloads or extra tools. All in a single cloud workspace with AI built in.

Get started free

Create and deploy websites, automations, internal tools, data pipelines and more in any programming language without setup, downloads or extra tools. All in a single cloud workspace with AI built in.