Parsing Datetimes with strptime in Python – Complete Guide for Data Science 2026
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
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
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