Call the .strftime(format_string) method on a datetime.date or datetime.datetime object—or embed the format specification directly inside an f-string (f"{dt:%B %d, %Y}")—using standard C-style % directives like %Y (4-digit year), %m (zero-padded month), %d (zero-padded day), and %H:%M:%S (24-hour time).
Basic Example
from datetime import date, datetime
today = date(2026, 11, 28)
now = datetime(2026, 11, 28, 14, 35, 9)
# 1. Recommended: Using .strftime() on date or datetime objects
print(today.strftime("%B %d, %Y")) # Output: November 28, 2026
print(today.strftime("%a, %d %b %Y")) # Output: Sat, 28 Nov 2026
print(now.strftime("%Y-%m-%d %I:%M %p")) # Output: 2026-11-28 02:35 PM
# 2. Concise f-string shorthand (calls __format__ -> strftime automatically)
print(f"Report generated on {now:%A, %B %d, %Y at %H:%M}")
# Output: Report generated on Saturday, November 28, 2026 at 14:35
Key Details & Edge Cases
- Unpadded day or hour values (
%-don Linux/macOS vs.%#don Windows):- Standard
%d,%m, and%Izero-pad single digits ("05"). - Stripping leading zeros uses platform-specific C
strftimeflags:%-dworks on Linux/macOS (raisingValueError: Invalid format stringon Windows), while%#dworks on Windows (and prints literallyon Linux/macOS). - For portable unpadded dates across all operating systems, format the day directly in an f-string:
f"{dt:%B} {dt.day}, {dt:%Y}"("November 5, 2026").
- Standard
- Avoid time directives (
%H,%M,%S,%I,%p) on adatetime.dateobject:datetime.datestores only year, month, and day. Passing time codes likedate.today().strftime("%H:%M")silently outputs"00:00"instead of raising an error—usedatetime.now()whenever time formatting is needed.
- Timezone-aware formatting (
%Zand%z):- On a naive
datetime.now(),%Zand%zevaluate to empty strings"". Attach a timezone viazoneinfo.ZoneInfo(datetime.now(ZoneInfo("Asia/Karachi"))) so%Zoutputs"PKT"and%zoutputs"+0500".
- On a naive
- Locale-dependent weekday and month names (
%A,%B,%p):- Month names (
%B/%b), weekday names (%A/%a), and AM/PM markers (%p) follow the process’s activelocale.LC_TIMEsetting (defaulting to English"C"locale in Python unlesslocale.setlocale()was called).
- Month names (
- Parsing strings back into dates (
strptimevs.strftime):- Remember
strftime= string format time (date object $\rightarrow$str), whereasdatetime.strptime(text, fmt)= string parse time (str$\rightarrow$datetimeobject).
- Remember
Common strftime Format Directives Reference
| Directive | Meaning | Example Output | Notes / Alternatives |
|---|---|---|---|
%Y / %y |
4-digit year / 2-digit zero-padded year | 2026 / 26 |
Prefer %Y to avoid century ambiguity. |
%m / %B / %b |
Month number (01–12) / Full name / Abbreviated |
11 / November / Nov |
%B and %b depend on system LC_TIME locale. |
%d / %j |
Day of month (01–31) / Day of year (001–366) |
28 / 332 |
Use dt.day in an f-string for portable unpadded days. |
%A / %a / %w |
Full weekday / Abbreviated weekday / Weekday index (0=Sun) |
Saturday / Sat / 6 |
Use %u (1=Mon to 7=Sun) for ISO weekday numbers. |
%H / %I / %p |
24-hour (00–23) / 12-hour (01–12) / AM or PM |
14 / 02 / PM |
Pair %I with %p when displaying 12-hour clocks. |
%M / %S / %f |
Minute (00–59) / Second (00–59) / Microsecond (000000) |
35 / 09 / 482190 |
Slice [:3] on %f output if milliseconds are needed. |
%Z / %z |
Timezone name / UTC offset (+HHMM) |
PKT / +0500 |
Requires timezone-aware datetime (ZoneInfo). |
|
Literal percent sign | % |
Required whenever mixing literal % text with format codes. |
You must log in or register to comment.
