How do you format and print a Python date in a custom readable format? | A1Lab@MZeeshanM to PythonEnglish • 4 days ago

How do you format and print a Python date in a custom readable format?

message-square
0

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 (%-d on Linux/macOS vs. %#d on Windows):
    • Standard %d, %m, and %I zero-pad single digits ("05").
    • Stripping leading zeros uses platform-specific C strftime flags: %-d works on Linux/macOS (raising ValueError: Invalid format string on Windows), while %#d works on Windows (and prints literally #d on 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").
  • Avoid time directives (%H, %M, %S, %I, %p) on a datetime.date object:
    • datetime.date stores only year, month, and day. Passing time codes like date.today().strftime("%H:%M") silently outputs "00:00" instead of raising an error—use datetime.now() whenever time formatting is needed.
  • Timezone-aware formatting (%Z and %z):
    • On a naive datetime.now(), %Z and %z evaluate to empty strings "". Attach a timezone via zoneinfo.ZoneInfo (datetime.now(ZoneInfo("Asia/Karachi"))) so %Z outputs "PKT" and %z outputs "+0500".
  • 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 active locale.LC_TIME setting (defaulting to English "C" locale in Python unless locale.setlocale() was called).
  • Parsing strings back into dates (strptime vs. strftime):
    • Remember strftime = string format time (date object $\rightarrow$ str), whereas datetime.strptime(text, fmt) = string parse time (str $\rightarrow$ datetime object).

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.