You’ve seen it before—some CSV or API gives you a weird string like "2025-04-10 15:45:00" and you think, “Cool, but how do I work with this?”
Say hello to strptime() — the friendly counterpart to strftime(). While strftime formats datetime objects into strings, strptime does the reverse: it parses strings into datetime objects.
strftime() can be read in detail here – https://brontowise.com/2025/05/18/mastering-strftime-in-python/
strptime() Explained
strptime stands for:
String Parse Time
It allows you to convert a string representing a date/time into a properdatetimeobject that you can calculate with, format, or use in logic.
Syntax:
from datetime import datetime
datetime.strptime(date_string, format)
date_string: The raw date/time string.format: The pattern that tells Python how to read that string.
Example 1: Parse a simple date string
from datetime import datetime
date_str = "2025-04-10"
parsed_date = datetime.strptime(date_str, "%Y-%m-%d")
print(parsed_date)
# Output: 2025-04-10 00:00:00
Boom 💥 — now parsed_date is a real datetime object.
Example 2: Include time too
date_str = "10/04/2025 15:45"
parsed_date = datetime.strptime(date_str, "%d/%m/%Y %H:%M")
print(parsed_date)
# Output: 2025-04-10 15:45:00
Notice how the format string matches the structure of the input string exactly — that’s the trick to getting it right.
Format Code Recap (Cheat Sheet)
| Code | Meaning | Example |
|---|---|---|
%Y | 4-digit year | 2025 |
%m | 2-digit month | 04 |
%d | 2-digit day | 10 |
%H | Hour (24-hour) | 15 |
%M | Minute | 45 |
%S | Second | 00 |
You’ll often mix and match these depending on your input string.
Example 3: Parsing logs
log_timestamp = "Apr 10 2025 03:45PM"
dt = datetime.strptime(log_timestamp, "%b %d %Y %I:%M%p")
print(dt)
# Output: 2025-04-10 15:45:00
Perfect for log parsing or building dashboards.
⚠️ Gotchas to Watch Out For
- The format must match exactly — spacing, colons, slashes — everything.
- If there’s a mismatch, Python throws a
ValueError. strptime()returns adatetime, not just adate. If you only want adate, use.date()on the result.
📌 TL;DR
- Use
strptime()to convert strings into datetime objects. - Perfect for parsing dates from user input, APIs, or CSV files.
- Combine with
strftime()for total datetime control.
“Time flies over us, but leaves its shadow behind.”
— Nathaniel Hawthorne