Skip to main content
Dates

How to parse a date string in Python

Quick answer

datetime.strptime(s, fmt) parses a specific format. datetime.fromisoformat(s) parses ISO 8601 with no format arg needed.

from datetime import datetime

dt = datetime.strptime("2026-08-01", "%Y-%m-%d")
print(dt)   # 2026-08-01 00:00:00

iso = datetime.fromisoformat("2026-08-01T15:30:00+00:00")
print(iso)  # 2026-08-01 15:30:00+00:00

strptime is the inverse of strftime β€” same format codes. When the input string matches your format exactly, you get a datetime back; on any mismatch it raises ValueError.

For ISO 8601 strings (dates from APIs, JSON payloads, most modern systems), datetime.fromisoformat is the winning shortcut β€” no format string needed, handles the timezone offset correctly, and is faster than strptime.

For fuzzy human-typed input ('July 4th, 2026', 'yesterday'), reach for the third-party dateutil.parser.parse β€” it accepts almost anything but is 100x slower than strptime, so use it only where you need the flexibility.

Variations

ISO 8601 with fromisoformat

from datetime import datetime
dt = datetime.fromisoformat("2026-08-01T15:30:00+00:00")

Python 3.11+ accepts every ISO variant including the trailing Z.

Format with 12-hour time

dt = datetime.strptime("08/01/2026 03:30 PM", "%m/%d/%Y %I:%M %p")

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

Fuzzy human input

from dateutil.parser import parse
parse("Aug 1st, 2026 at 3:30 PM")

Requires pip install python-dateutil. Slower but far more forgiving.

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