Coding

Python strftime Format Codes: Cheat Sheet with Examples

In Python, strftime turns a datetime into a string using % codes: datetime.now().strftime("%Y-%m-%d %H:%M:%S") gives 2026-11-06 14:05:09. The codes you need most are %Y (year), %m (month), %d (day), %H (24-hour), %I (12-hour), %M (minute), %S (second) and %p (AM/PM).

Every output on this page was produced with Python 3.12 on Windows from this datetime, so you can reproduce it exactly:

from datetime import datetime
d = datetime(2026, 11, 6, 14, 5, 9, 123456)   # Friday 6 November 2026, 14:05:09.123456

Common date and time formats

You wantFormat stringOutput
ISO date%Y-%m-%d2026-11-06
European date%d/%m/%Y06/11/2026
US date, 2-digit year%m/%d/%y11/06/26
24-hour time%H:%M:%S14:05:09
12-hour time%I:%M %p02:05 PM
Long date%A, %B %d, %YFriday, November 06, 2026
Short date%a %b %dFri Nov 06
Timestamp for logs%Y-%m-%dT%H:%M:%S2026-11-06T14:05:09
Sortable file name%Y%m%d_%H%M%S20261106_140509

Full format code reference

CodeMeaningOutput for d
%YYear with century2026
%yYear without century, zero-padded26
%mMonth, 01–1211
%B / %bMonth name, full / abbreviated (locale)November / Nov
%dDay of month, 01–3106
%jDay of year, 001–366310
%A / %aWeekday name, full / abbreviated (locale)Friday / Fri
%wWeekday number, Sunday = 05
%uISO weekday number, Monday = 15
%HHour, 00–2314
%IHour, 01–1202
%pAM or PM (locale)PM
%MMinute, 00–5905
%SSecond, 00–5909
%fMicrosecond, 6 digits123456
%UWeek of year, Sunday first, 00–5344
%WWeek of year, Monday first, 00–5344
%VISO 8601 week number45
%GISO 8601 week-based year2026
%zUTC offset, +HHMMempty (naive datetime)
%ZTime zone nameempty (naive datetime)
%cLocale's date and timeFri Nov 6 14:05:09 2026
%x / %XLocale's date / time11/06/26 / 14:05:09
%%A literal % sign%

Note the week numbers: %U and %W say week 44 while ISO %V says week 45. They use different rules for where week 1 starts. If you need ISO 8601 week numbers, use %V together with %G, never %V with %Y: around New Year the ISO year can differ from the calendar year.

How to remove leading zeros (6 instead of 06)

This is the most common strftime problem, and the answer depends on the operating system. Python hands these codes to the platform's C library, and the "no padding" flag isn't part of the C standard:

  • Linux: %-d, %-m, %-I. The - flag is a glibc extension described as "Do not pad a numeric result string"; the man page notes that only "a few other systems" support similar flags, so check man strftime on macOS and BSD.
  • Windows: %#d, %#m, %#I. Microsoft's C runtime uses # to "Remove leading zeros".

Using the wrong one fails loudly on Windows. Real output from Python 3.12.2 on Windows:

>>> d.strftime("%-d")
ValueError: Invalid format string
>>> d.strftime("%#d")
'6'

For code that has to run everywhere, skip the flags and use the datetime attributes in an f-string:

f"{d.day}/{d.month}/{d.year}"     # '6/11/2026'
f"{d:%B} {d.day}, {d.year}"        # 'November 6, 2026'

strftime in f-strings

A datetime accepts the same codes directly in an f-string or format(), which is often shorter than calling the method:

f"{d:%Y-%m-%d %H:%M}"     # '2026-11-06 14:05'
"{:%d.%m.%Y}".format(d)    # '06.11.2026'

Time zones: %z, %:z and %Z

A plain datetime(...) or datetime.now() is naive: it has no time zone, and Python replaces %z, %:z and %Z with an empty string. Make it aware to get real values:

from datetime import datetime, timezone, timedelta

utc = datetime(2026, 11, 6, 14, 5, 9, tzinfo=timezone.utc)
utc.strftime("%Y-%m-%d %H:%M:%S %z %Z")   # '2026-11-06 14:05:09 +0000 UTC'

cet = datetime(2026, 11, 6, 14, 5, 9, tzinfo=timezone(timedelta(hours=2)))
cet.strftime("%z %:z %Z")                  # '+0200 +02:00 UTC+02:00'

%:z (offset with a colon, as ISO 8601 and RFC 3339 write it) was added to strftime in Python 3.12. On older versions, use isoformat() instead. For real named zones with daylight-saving rules, use zoneinfo.ZoneInfo("Europe/Vilnius") as the tzinfo. Windows has no IANA time zone database, so on Windows that line raises ZoneInfoNotFoundError: 'No time zone found with key Europe/Vilnius' until you run pip install tzdata; the zoneinfo documentation recommends declaring tzdata as a dependency in cross-platform projects.

Parsing strings back with strptime

strptime uses the same codes in the other direction. It is a class method, so call it on datetime:

datetime.strptime("06/11/2026 14:05", "%d/%m/%Y %H:%M")
# datetime.datetime(2026, 11, 6, 14, 5)

The string must match the format exactly, separators included, or you get a ValueError. Real output:

>>> datetime.strptime("2026-11-06", "%d/%m/%Y")
ValueError: time data '2026-11-06' does not match format '%d/%m/%Y'

When parsing, %z also accepts Z as UTC and offsets with a colon (since Python 3.7), and %f accepts one to six digits.

When to use isoformat instead

If you just need a standard machine-readable timestamp, isoformat() and fromisoformat() are simpler than any format string and round-trip exactly:

d.isoformat()                                   # '2026-11-06T14:05:09.123456'
utc.isoformat()                                 # '2026-11-06T14:05:09+00:00'
datetime.fromisoformat("2026-11-06T14:05:09Z")  # aware datetime in UTC

Use strftime for human-facing text and fixed legacy formats; use ISO 8601 for logs, APIs and anything another program will read.

Locale-dependent codes

%A, %a, %B, %b, %p, %c, %x and %X follow the current locale. The Python documentation gives the example that %p is AM/PM in en_US but am/pm in de_DE. If your output has to be identical on every machine (file names, CSV exports, API payloads), stick to the numeric codes.

Frequently asked questions

What is the difference between strftime and strptime?
strftime formats a datetime object into a string ('f' for format). strptime parses a string into a datetime ('p' for parse) and is called on the class: datetime.strptime('06/11/2026', '%d/%m/%Y'). Both use the same format codes.
How do I get milliseconds instead of microseconds?
%f always gives six digits of microseconds. For milliseconds, cut the last three digits: d.strftime('%H:%M:%S.%f')[:-3] gives 14:05:09.123. Alternatively use d.isoformat(timespec='milliseconds').
Why does %Z print nothing?
Because the datetime is naive, meaning it has no tzinfo. Python replaces %Z, %z and %:z with an empty string for naive datetimes. Create aware datetimes, for example datetime.now(timezone.utc), if you need the zone in the output.
Is strftime output the same on every computer?
Not entirely. Python passes most codes to the platform's C library, so codes outside the documented set (such as %-d) behave differently by OS, and locale-dependent codes such as %A, %B, %p, %c and %x change with the locale.

Sources