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 want | Format string | Output |
|---|---|---|
| ISO date | %Y-%m-%d | 2026-11-06 |
| European date | %d/%m/%Y | 06/11/2026 |
| US date, 2-digit year | %m/%d/%y | 11/06/26 |
| 24-hour time | %H:%M:%S | 14:05:09 |
| 12-hour time | %I:%M %p | 02:05 PM |
| Long date | %A, %B %d, %Y | Friday, November 06, 2026 |
| Short date | %a %b %d | Fri Nov 06 |
| Timestamp for logs | %Y-%m-%dT%H:%M:%S | 2026-11-06T14:05:09 |
| Sortable file name | %Y%m%d_%H%M%S | 20261106_140509 |
Full format code reference
| Code | Meaning | Output for d |
|---|---|---|
%Y | Year with century | 2026 |
%y | Year without century, zero-padded | 26 |
%m | Month, 01–12 | 11 |
%B / %b | Month name, full / abbreviated (locale) | November / Nov |
%d | Day of month, 01–31 | 06 |
%j | Day of year, 001–366 | 310 |
%A / %a | Weekday name, full / abbreviated (locale) | Friday / Fri |
%w | Weekday number, Sunday = 0 | 5 |
%u | ISO weekday number, Monday = 1 | 5 |
%H | Hour, 00–23 | 14 |
%I | Hour, 01–12 | 02 |
%p | AM or PM (locale) | PM |
%M | Minute, 00–59 | 05 |
%S | Second, 00–59 | 09 |
%f | Microsecond, 6 digits | 123456 |
%U | Week of year, Sunday first, 00–53 | 44 |
%W | Week of year, Monday first, 00–53 | 44 |
%V | ISO 8601 week number | 45 |
%G | ISO 8601 week-based year | 2026 |
%z | UTC offset, +HHMM | empty (naive datetime) |
%Z | Time zone name | empty (naive datetime) |
%c | Locale's date and time | Fri Nov 6 14:05:09 2026 |
%x / %X | Locale's date / time | 11/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 checkman strftimeon 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.