Convert datetime object to a String of date only in Python
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.
Introduction
Converting a Python datetime to a date-only string is a common formatting operation for reports, APIs, and file naming. The usual approach is strftime, but correct formatting depends on timezone handling and whether you want local or UTC date semantics. A robust solution should avoid accidental timezone shifts and keep format conventions explicit.
Core Sections
1. Basic date-only string with strftime
This yields ISO-like date string such as 2026-03-03.
2. Use .date().isoformat()
isoformat() is concise and avoids manual format tokens.
3. Timezone-aware conversion first
If datetime is UTC but output should be local date:
Convert timezone before extracting date.
4. Parsing then formatting
Useful when input comes from serialized timestamps.
5. Pandas/vectorized equivalent
Use vectorized operations for large datasets.
6. API contract consistency
Pick one date format (typically YYYY-MM-DD) and document it for all external interfaces to avoid parsing ambiguity.
Common Pitfalls
- Extracting date before converting UTC to target timezone.
- Mixing locale-specific formats with machine-readable APIs.
- Using naive datetimes in timezone-sensitive applications.
- Repeated parsing/formatting in loops instead of vectorized operations.
- Inconsistent date string formats across service boundaries.
Summary
Convert datetime to date-only strings using strftime("%Y-%m-%d") or .date().isoformat(), and handle timezone conversion before truncating time when required. Clear format conventions and consistent timezone rules prevent subtle date bugs in data pipelines and APIs.
Related reading
- Convert datetime to Unix timestamp and convert it back in python
- Convert dictionary values into array
- Convert Django Model object to dict with all of the fields intact
- Convert floats to ints in Pandas?
- Convert hex string to integer in Python
- Convert hex string to integer in Python
- Convert int to binary string in Python
- Convert int to binary string in Python
.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.