Skip to main content
Dates

How to format a date in Python

Quick answer

Use dt.strftime('%Y-%m-%d') for custom formats or dt.isoformat() for the ISO 8601 standard.

from datetime import datetime, UTC

now = datetime.now(UTC)
print(now.strftime("%Y-%m-%d %H:%M:%S"))  # '2026-08-01 15:30:00'
print(now.strftime("%B %d, %Y"))          # 'August 01, 2026'
print(now.isoformat())                      # '2026-08-01T15:30:00.123456+00:00'

strftime uses format codes: %Y = 4-digit year, %m = zero-padded month, %d = zero-padded day, %H = 24h hour, %M = minute, %S = second. The full list is at docs.python.org/3/library/datetime.html#format-codes.

For machine-readable output (APIs, databases, logs) prefer .isoformat() β€” it's the ISO 8601 standard, always sortable as text, and unambiguously parseable back into a datetime.

For human-facing output, keep the format in ONE place (a constant like DATE_FMT = '%b %d, %Y') so a locale change touches one file, not fifty.

Variations

Just the date part

print(now.date().isoformat())  # '2026-08-01'

date() strips the time.

Just the time part

print(now.time().isoformat())  # '15:30:00.123456'

time() strips the date.

12-hour with AM/PM

print(now.strftime("%I:%M %p"))  # '03:30 PM'

%I is 12-hour hour; %p is AM/PM.

Practise this in your browser

Every how-to has a live lesson. Free tier, no card.

Start free β†’

Unlock every lesson

Pro β€” $12/mo, unlimited AI, cancel any time.

See Pro plans β†’

Get one Python lesson + one career idea every Friday

No spam, no "buy our course now". Three bullets, every Friday. Unsubscribe with one click.

Related how-tos