If you’ve ever pulled a datetime value in Python and thought, “Ugh, what even is this format?” — you’re not alone.
Python gives us strftime() for that exact reason. Whether you want to show 2025-04-10 as “10 April, 2025” or “Thursday 10th of April 2025, 03:45 PM” — strftime has your back. Let’s decode it in this quick post.
What is strftime()?
The function strftime() stands for:
“String Format Time”
It lets you convert adatetimeobject into a nicely formatted string.
You can think of it as a way to custom print your dates and times — exactly how you want.
Real Life Use Case:
You’re generating a daily report and want the filename to include today’s date in the format report_2025_04_10.csv. Here’s where strftime() shines:
from datetime import datetime
today = datetime.now()
filename = today.strftime("report_%Y_%m_%d.csv")
print(filename)
# Output: report_2025_04_10.csv
Neat, right?
📅 Common Format Codes (Cheat Sheet)
| Code | Meaning | Example |
|---|---|---|
%Y | Year (4-digit) | 2025 |
%y | Year (2-digit) | 25 |
%m | Month (zero-padded) | 04 |
%B | Full month name | April |
%b | Short month name | Apr |
%d | Day of month (zero-padded) | 10 |
%A | Full weekday name | Thursday |
%a | Abbreviated weekday | Thu |
%H | Hour (24-hr) | 15 |
%I | Hour (12-hr) | 03 |
%p | AM/PM | PM |
%M | Minutes | 45 |
%S | Seconds | 09 |
More Examples!
1. Format for user-friendly logs:
log_time = today.strftime("%A %d %B %Y, %I:%M %p")
print(log_time)
# Output: Thursday 10 April 2025, 03:45 PM
2. Filename-friendly timestamp:
timestamp = today.strftime("%Y%m%d_%H%M%S")
print(timestamp)
# Output: 20250410_154509
3. Only time:
clock = today.strftime("%H:%M:%S")
print(clock)
# Output: 15:45:09
✍️ A Quick Tip:
The opposite of strftime() is strptime() — it lets you parse a date string into a datetime object. Think of it as string to time.
More about strptime() can be read here – https://brontowise.com/2025/05/21/parsing-dates-with-strptime-in-python/
📦 Summary
strftime()formats yourdatetimeobject to strings.- Super handy in reports, filenames, dashboards, and logs.
- Endless customization using format codes.
So next time you see a scary-looking datetime object, just whisper: “I know strftime.” 💁♂️
“Time is what we want most, but what we use worst.”
— William Penn