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.
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.
If you need only the date component:
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.
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:
Named-zone example using zoneinfo:
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.
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.
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.
Another pattern is generating SQL date filters:
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.
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
strftimebased 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
- Frequency counts for unique values in a NumPy array
- from ... import vs import .
- From conda create requirements.txt for pip3
- from kafka import KafkaClient ImportError No module named kafka
- from keras.backend.tensorflow_backend import set_session
- From list of integers, get number closest to a given value
- from torch._C import ImportError DLL load failed The specified module could not be found
- from utils import label_map_util Import Error No module named utils
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseTrack 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.