Parsing Datetimes with strptime in Python
When your data comes as strings (logs, CSVs, APIs, user input), you need to convert those strings into proper datetime objects. The datetime.strptime() method is the standard, precise way to do this when you know the exact format of the date string. In 2026, mastering strptime is essential for clean data ingestion and reliable time-based feature engineering.
TL;DR — How strptime Works
datetime.strptime(string, format)→ parses string into datetime object- You must provide the exact format using format codes
- Very fast and reliable when the format is known
- Use pandas
pd.to_datetime()for large datasets or unknown formats
1. Basic strptime Usage
from datetime import datetime
date_str = "2026-03-19 14:30:25"
dt = datetime.strptime(date_str, "%Y-%m-%d %H:%M:%S")
print(dt)
print(dt.year, dt.month, dt.day, dt.hour)
2. Common Format Codes (Most Used in Data Science)
# Popular formats
print(datetime.strptime("2026-03-19", "%Y-%m-%d"))
print(datetime.strptime("19/03/2026", "%d/%m/%Y"))
print(datetime.strptime("March 19, 2026", "%B %d, %Y"))
print(datetime.strptime("2026-03-19 14:30", "%Y-%m-%d %H:%M"))
3. Real-World Data Science Examples
import pandas as pd
# Demo log file so this example runs as-is
pd.DataFrame({"timestamp_str": ["2026-03-19 14:30:25", "2026-03-19 15:02:10", "2026-03-20 09:15:00"]}).to_csv("logs.csv", index=False)
df = pd.read_csv("logs.csv")
# Example 1: Parse known format column
df["timestamp"] = df["timestamp_str"].apply(
lambda x: datetime.strptime(x, "%Y-%m-%d %H:%M:%S")
)
# Example 2: Vectorized parsing with pandas (faster for large data)
df["timestamp"] = pd.to_datetime(df["timestamp_str"], format="%Y-%m-%d %H:%M:%S")
# Example 3: Handling multiple possible formats
def safe_parse(s):
for fmt in ("%Y-%m-%d %H:%M:%S", "%d/%m/%Y %H:%M", "%B %d, %Y"):
try:
return datetime.strptime(s, fmt)
except ValueError:
continue
return None
4. Best Practices in 2026
- Use
strptimewhen the format is known and consistent - Prefer pandas
pd.to_datetime(format=...)for large datasets - For messy or unknown formats, use
dateutil.parserorpendulum.parse() - Always make the resulting datetime timezone-aware
- Store the original string column for debugging
How strptime Parsing Works
datetime.strptime(text, format) reads a string using the same codes as strftime. The format must match the text exactly, including separators; otherwise a ValueError explains what did not match.
For columns, pd.to_datetime with an explicit format is much faster than calling strptime row by row, and errors="coerce" turns unparseable values into NaT instead of failing.
When several formats appear in one column, parse with each format separately and combine the results with fillna.
Worked Example: Mixed Formats in One Column
A column with two date formats and one bad value is parsed safely.
import pandas as pd
raw = pd.Series(["2026-03-19 14:30:25", "19/03/2026 09:15", "not a date", "2026-03-20 08:00:00"])
iso = pd.to_datetime(raw, format="%Y-%m-%d %H:%M:%S", errors="coerce")
dmy = pd.to_datetime(raw, format="%d/%m/%Y %H:%M", errors="coerce")
parsed = iso.fillna(dmy)
print(parsed.tolist())
print(int(parsed.isna().sum()), "value could not be parsed")
The ISO values parse with the first format and the day-first value with the second. Combining them with fillna leaves only "not a date" as NaT, so one value is reported as unparseable.
Practical Tips
Write down the expected format of every date column in the data source description. Explicit formats make parsing faster and protect you from day-month mix-ups such as 03/04/2026, which could mean 3 April or 4 March.
After parsing, check the minimum and maximum dates. Values far in the past or future usually reveal a wrong format or a typing error in the source data.
Keep parsing code in one function so every script reads dates the same way.
Passing format= explicitly also silences pandas warnings about inferring formats, keeping the script output clean. Store the format strings as named constants so they are easy to find and update when a data source changes.
Common Mistakes
- Using a format that does not match separators.
- Calling strptime in a loop over large columns.
- Letting pandas guess ambiguous day-first dates.
- Ignoring values that became NaT.
Quick Summary
- strptime needs an exact format match.
- pd.to_datetime(format=...) is fast for columns.
- errors="coerce" marks bad values as NaT.
- Combine multiple formats with fillna.
Conclusion
strptime is the precise tool for converting known-format date strings into datetime objects. In 2026 data science, it is used heavily for clean data ingestion, especially when dealing with logs, CSVs, and APIs that have fixed timestamp formats. Combine it with pandas vectorized methods for maximum performance on large datasets.
Next steps:
- Take one of your datasets with date strings and parse them using
strptimeor pandasto_datetime