Parsing Dates with strptime() in Python

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 proper datetime object 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.

Advertisements

Format Code Recap (Cheat Sheet)

CodeMeaningExample
%Y4-digit year2025
%m2-digit month04
%d2-digit day10
%HHour (24-hour)15
%MMinute45
%SSecond00

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 a datetime, not just a date. If you only want a date, 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

Advertisements

Leave a comment

Website Powered by WordPress.com.

Up ↑

Discover more from BrontoWise

Subscribe now to keep reading and get access to the full archive.

Continue reading