Python
Date Manipulation
Programming
Python datetime
Python Tips

Formatting yesterday's date in python

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

Formatting yesterday's date sounds simple, but small details such as timezone handling and business-day rules can change the output significantly. In Python, the safest baseline is to compute yesterday with timedelta(days=1) and then format with strftime. From there, you can extend logic for UTC, local zones, and reporting requirements.

Basic Calendar-Day Calculation

For simple scripts, subtract one day from current datetime.

python
1from datetime import datetime, timedelta
2
3now = datetime.now()
4yesterday = now - timedelta(days=1)
5
6print("Now:", now)
7print("Yesterday:", yesterday)

If you need only the date component:

python
1from datetime import datetime, timedelta
2
3yesterday_date = (datetime.now() - timedelta(days=1)).date()
4print(yesterday_date)

This avoids accidentally carrying time fields into APIs that expect a date string.

Format Yesterday with strftime

Use a format that matches your consumer system.

python
1from datetime import datetime, timedelta
2
3yesterday = datetime.now() - timedelta(days=1)
4
5print(yesterday.strftime("%Y-%m-%d"))
6print(yesterday.strftime("%d/%m/%Y"))
7print(yesterday.strftime("%Y%m%d"))
8print(yesterday.strftime("%a, %b %d %Y"))

Common directives:

  • '%Y: year'
  • '%m: month with leading zero'
  • '%d: day with leading zero'
  • '%H, %M, %S: time components'

Choose one canonical machine format for automation, usually ISO-like patterns.

Timezone-Aware Yesterday

If jobs run across regions, timezone-aware datetimes are safer than naive local values.

UTC example:

python
1from datetime import datetime, timedelta, timezone
2
3now_utc = datetime.now(timezone.utc)
4yesterday_utc = now_utc - timedelta(days=1)
5
6print(now_utc.isoformat())
7print(yesterday_utc.isoformat())

Named-zone example using zoneinfo:

python
1from datetime import datetime, timedelta
2from zoneinfo import ZoneInfo
3
4tz = ZoneInfo("America/Toronto")
5now_local = datetime.now(tz)
6yesterday_local = now_local - timedelta(days=1)
7
8print(now_local.strftime("%Y-%m-%d %H:%M:%S %Z"))
9print(yesterday_local.strftime("%Y-%m-%d %H:%M:%S %Z"))

This handles daylight-saving transitions using IANA timezone rules.

Parse Input Date and Return Previous Day

Many applications receive date strings and need previous day in same format.

python
1from datetime import datetime, timedelta
2
3
4def previous_day(date_str: str, fmt: str = "%Y-%m-%d") -> str:
5    dt = datetime.strptime(date_str, fmt)
6    return (dt - timedelta(days=1)).strftime(fmt)
7
8
9print(previous_day("2026-03-05"))
10print(previous_day("05/03/2026", "%d/%m/%Y"))

Wrapping this in a function keeps parsing logic centralized and testable.

Business-Day Variant

In reporting contexts, yesterday may mean previous business day instead of previous calendar day.

python
1from datetime import date, timedelta
2
3
4def previous_business_day(d: date) -> date:
5    current = d - timedelta(days=1)
6    while current.weekday() >= 5:
7        current -= timedelta(days=1)
8    return current
9
10
11print(previous_business_day(date(2026, 3, 9)))  # Monday -> Friday

For finance workflows, extend this with a holiday calendar list.

File Naming and Query Use Cases

A common pattern is to include yesterday in report filenames.

python
1from datetime import datetime, timedelta
2
3run_day = datetime.now() - timedelta(days=1)
4filename = f"transactions_{run_day.strftime('%Y%m%d')}.csv"
5print(filename)

Another pattern is generating SQL date filters:

python
1from datetime import datetime, timedelta
2
3y = (datetime.now() - timedelta(days=1)).strftime("%Y-%m-%d")
4query = f"SELECT * FROM orders WHERE order_date = '{y}'"
5print(query)

In production, use query parameters instead of string interpolation when sending SQL.

Testing Date Logic Deterministically

Avoid depending on real clock time in tests. Inject a fixed base datetime.

python
1from datetime import datetime, timedelta
2
3
4def format_yesterday(base: datetime, fmt: str = "%Y-%m-%d") -> str:
5    return (base - timedelta(days=1)).strftime(fmt)
6
7
8fixed = datetime(2026, 1, 1, 8, 0, 0)
9print(format_yesterday(fixed))  # 2025-12-31

This catches month and year boundary cases without flaky tests.

Common Pitfalls

A frequent pitfall is mixing timezone-aware and naive datetimes in one calculation. Python will raise errors or produce inconsistent behavior.

Another issue is assuming yesterday always means exactly 24 hours ago. Business definitions are often calendar-based in a specific timezone.

Teams also use locale-dependent string formats for machine integrations, which can break parsers in other environments.

Boundary dates such as month-end and year-end are often under-tested and lead to production defects.

Finally, for business-day logic, skipping holiday handling can create off-by-one reporting errors.

Summary

  • Use timedelta(days=1) as the baseline way to compute yesterday.
  • Format output with strftime based on consumer requirements.
  • Prefer timezone-aware datetimes for distributed systems.
  • Separate calendar-day and business-day semantics in code.
  • Inject fixed base times in tests to validate boundary behavior.

Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.