Ah, Python dates. You never quite realize how much of a mess they are—until you’re knee-deep in some API response with a timestamp like "2025-04-10T14:30:00Z" and someone asks you to make sense of it.
Enter the Batman and Robin of Python’s datetime module:
👉 strftime() — the Formatter
👉 strptime() — the Parser
Let’s break this dynamic duo down. Who does what, when to use whom, and how they work together like peanut butter & jelly 🥜🍇.
The TL;DR: Who Does What?
| Function | Role | Use Case |
|---|---|---|
strftime() | Format datetime → string | When you want to display a nice date. |
strptime() | Parse string → datetime | When you want to read a raw string. |
Example: strftime() – “Make it Pretty”
from datetime import datetime
now = datetime.now()
print(now.strftime("%Y-%m-%d %H:%M:%S"))
# Output: 2025-04-10 16:55:23
More on strftime() here – https://brontowise.com/2025/05/18/mastering-strftime-in-python/
Think of strftime() as the person who takes your chaotic datetime object and dresses it up for presentation.
💡 “Hey boss, here’s your date, nice and tidy!”
Example: strptime() – “Make it Usable”
from datetime import datetime
date_str = "10/04/2025 04:30 PM"
dt = datetime.strptime(date_str, "%d/%m/%Y %I:%M %p")
print(dt)
# Output: 2025-04-10 16:30:00
More on strptime() here – https://brontowise.com/2025/05/21/parsing-dates-with-strptime-in-python/
This one is the detective—analyzing raw clues (strings) and converting them into objects Python can work with.
💡 “Got it, chief. That string is actually a datetime in disguise!”
The Real-World Analogy
Imagine you’re reading and writing a diary:
- 📝
strptime()is you reading an entry: “April 10, 2025? Ah yes, that was the day I discovered list comprehensions.” - ✍️
strftime()is you writing a new one, formatting the date as"2025-04-10"before scribbling your thoughts.
They’re opposites, yet equally important.
Common Pitfalls
- The format string must match exactly in
strptime()— get one%wrong and you’ll meet Mr.ValueError. strftime()won’t complain, but you’ll get garbage if you choose wrong format codes.- And nope,
%Y/%m/%dis not the same as%m/%d/%Y.
📋 Handy Format Cheat Sheet
| Code | Meaning | Example |
|---|---|---|
%Y | Year (4 digits) | 2025 |
%m | Month (01-12) | 04 |
%d | Day (01-31) | 10 |
%H | Hour (00-23) | 16 |
%I | Hour (01-12) | 04 |
%p | AM/PM | PM |
%M | Minute | 55 |
%S | Second | 23 |
When to Use What?
- Use
strptime()when data comes from outside – CSVs, APIs, user input. - Use
strftime()when you’re preparing data to go outside – reports, logs, filenames.
Final Thought
“Time is what we want most, but what we use worst.”
— William Penn
With strptime() and strftime(), at least in code, you can use time wisely 😉
Leave a comment