Parsing datetimes with strptime is Python’s standard way to convert date/time strings into datetime objects — essential for reading logs, API responses, CSV/JSON data, database timestamps, or user input. The datetime.strptime() method takes two arguments: the string to parse and a format string using % directives that match the input layout exactly. In 2026, accurate parsing remains critical — mismatched formats cause ValueError, and robust parsing with explicit formats prevents bugs in data pipelines, ETL jobs, analytics, and production systems. While dateutil.parser is lenient, strptime() with strict formats is preferred for reliability and speed.
Here’s a complete, practical guide to parsing datetimes with strptime: syntax, common format codes, ISO 8601 examples, error handling, pandas/Polars integration, real-world patterns, and modern best practices for safety, performance, and scalability.
Basic usage: pass the input string and a matching format string — strptime() returns a datetime object if successful, or raises ValueError on mismatch.
from datetime import datetime
# ISO 8601 datetime with microseconds and UTC
iso_str = "2026-02-10T14:30:45.123456Z"
dt = datetime.strptime(iso_str, "%Y-%m-%dT%H:%M:%S.%fZ")
print(dt) # 2026-02-10 14:30:45.123456
Common format codes and examples — match the input string exactly, including separators and padding.
# Date only
date_str = "2026-02-10"
dt_date = datetime.strptime(date_str, "%Y-%m-%d")
print(dt_date) # 2026-02-10 00:00:00
# US-style date + 12-hour time
us_str = "02/10/2026 02:30:45 PM"
dt_us = datetime.strptime(us_str, "%m/%d/%Y %I:%M:%S %p")
print(dt_us) # 2026-02-10 14:30:45
# Log format with weekday
log_str = "Tue Feb 10 14:30:45 2026"
dt_log = datetime.strptime(log_str, "%a %b %d %H:%M:%S %Y")
print(dt_log) # 2026-02-10 14:30:45
# Short date + time (no seconds)
short_str = "10-Feb-2026 14:30"
dt_short = datetime.strptime(short_str, "%d-%b-%Y %H:%M")
print(dt_short) # 2026-02-10 14:30:00
Real-world pattern: parsing timestamps from logs or CSV — use strict formats for reliability, handle errors gracefully.
log_lines = [
"2026-02-10T14:30:45Z INFO Starting process",
"2026-02-10T14:31:00Z ERROR Failed to connect",
]
timestamps = []
for line in log_lines:
try:
ts_str = line.split(" ")[0] # Extract timestamp
ts = datetime.strptime(ts_str, "%Y-%m-%dT%H:%M:%SZ")
timestamps.append(ts)
except ValueError:
print(f"Invalid timestamp: {line}")
print(timestamps)
Best practices make strptime() parsing safe and performant. Always use explicit format strings — avoid dateutil.parser in production for consistency and speed. Match the input exactly — include separators, padding, and timezone markers. Modern tip: use Polars for large timestamp columns — pl.col("ts_str").str.to_datetime("%Y-%m-%dT%H:%M:%S%z") is 10–100× faster than pandas to_datetime with format. Add type hints — datetime.datetime — improves readability and mypy checks. Handle errors — wrap in try/except ValueError — log invalid strings or use default values. For timezone-aware strings, include %z or Z — strptime(ts_str, "%Y-%m-%dT%H:%M:%S%z") parses offset correctly. Use fromisoformat() (Python 3.7+) for ISO 8601 strings — faster and simpler than strptime. Validate after parsing — check dt.year >= 1900 or reasonable ranges. Combine with pandas/Polars — pd.to_datetime(df['ts'], format="%Y-%m-%dT%H:%M:%S") for vectorized parsing.
Parsing datetimes with strptime turns strings into usable datetime objects — accurate, fast, and reliable when formats match exactly. In 2026, use explicit formats, handle errors, vectorize in pandas/Polars, and prefer fromisoformat() for ISO. Master strptime, and you’ll ingest timestamps from logs, APIs, CSVs, and databases cleanly and correctly.
Next time you have a date/time string — parse it with strptime. It’s Python’s cleanest way to say: “Turn this string into a real datetime.”