Parsing Datetimes with strptime in Python

Dates And Time Mar 19, 2026

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 strptime when the format is known and consistent
  • Prefer pandas pd.to_datetime(format=...) for large datasets
  • For messy or unknown formats, use dateutil.parser or pendulum.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 strptime or pandas to_datetime

Related Tutorials

Share:
Last updated: March 2026
Built-in Functions in Python 2026 str() in Python 2026: String Conversion + Modern Formatting & Best Practices memoryview with JAX in Python 2026: Zero-Copy NumPy → JAX Array Interop + Efficient ML Examples memoryview with TensorFlow in Python 2026: Zero-Copy NumPy → Tensor Interop + GPU Pinning & ML Examples memoryview with TensorFlow in Python 2026: Zero-Copy NumPy → Tensor Interop + ML Examples memoryview with NumPy & PyTorch in Python 2026: Zero-Copy Views, Efficient Slicing & ML Interop Examples memoryview with NumPy in Python 2026: Zero-Copy Views, Efficient Slicing & Real ML Examples memoryview() in Python 2026: Zero-Copy Magic for Large Binary Data + Real Examples import() in Python 2026: How It Works, Security Risks & Modern Alternatives (importlib) zip() in Python 2026: How to Use It, strict=True Behavior & Real-World Examples vars() in Python 2026: Accessing Object Namespace + Modern Introspection Patterns type() in Python 2026: Dynamic Type Inspection & Object Creation + Modern Patterns tuple() in Python 2026: Immutable Sequences + Modern Patterns & Best Practices super() in Python 2026: Method Resolution & Modern Inheritance Patterns sum() in Python 2026: Summing Iterables + Modern Numeric Patterns & Best Practices staticmethod() in Python 2026: Static Methods, Utility Functions & Modern Best Practices sorted() in Python 2026: Sorting Iterables + Modern Patterns & Best Practices slice() in Python 2026: Creating Slice Objects + Modern Patterns & Best Practices setattr() in Python 2026: Dynamic Attribute Setting + Modern Patterns & Safety set() in Python 2026: Mutable Sets Creation + Modern Patterns & Best Practices