Mastering strftime() in Python

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 a datetime object 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)

CodeMeaningExample
%YYear (4-digit)2025
%yYear (2-digit)25
%mMonth (zero-padded)04
%BFull month nameApril
%bShort month nameApr
%dDay of month (zero-padded)10
%AFull weekday nameThursday
%aAbbreviated weekdayThu
%HHour (24-hr)15
%IHour (12-hr)03
%pAM/PMPM
%MMinutes45
%SSeconds09
Advertisements

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 your datetime object 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

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