How to Format a Date and Time as Text in Python with strftime
A date and time often has to become text: in a file or folder name, in a log line, in a message. strftime writes a datetime in the exact layout you describe with format codes. This guide formats one moment two ways, with real output from Python 3.15.2.
Syntax
<moment>.strftime(<format>)
| Part | What it means |
|---|---|
<moment> | A datetime |
<format> | Text with format codes such as %Y, the year, and %m, the month; everything else is copied as it is |
Python's datetime reference: "Return a string representing the date and time, controlled by an explicit format string."
The codes this guide uses: %Y year, %m month as a number, %d day, %H hour (00–23), %M minute, %S second, and %B the month's name.
Prerequisites
- uv and Python. This guide uses uv 0.13.10 with Python 3.15.2, in a project made with
uv init.
Step 1: Write the Script
One fixed moment, in UTC, so the output is the same every time:
from datetime import UTC, datetime
moment = datetime(2026, 11, 28, 13, 36, 55, tzinfo=UTC)
print(moment.strftime("%Y-%m-%d_%H-%M-%S"))
print(moment.strftime("%d %B %Y, %H:%M"))

Step 2: Run It
uv run python format_time.py
2026-11-28_13-36-55
28 November 2026, 13:36

The first layout suits file and folder names: it sorts in time order and has no colons. The second is for people.
Common Mistakes
| Mistake | What happens | Do this instead |
|---|---|---|
%M for the month | %M is the minute: "%Y-%M-%d" printed 2026-36-28 | Use %m for the month |
Colons in a file name: "%H:%M:%S" | Windows doesn't allow : in names; Microsoft's naming rules list it as reserved | Use - or _ between the parts |
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
| A month number that's too big, or changes every minute | %M where %m was meant | Use %m |
FAQ
Does %B always print English month names?
It prints them in the program's locale. This guide's run printed November.
Where's the full list of codes?
In the reference's table, strftime() and strptime() format codes.
Conclusion
moment.strftime("%Y-%m-%d_%H-%M-%S") printed 2026-11-28_13-36-55, a sortable name without colons, and "%d %B %Y, %H:%M" printed 28 November 2026, 13:36.
Additional Resources
- datetime.strftime — the method.
- Format codes — every code and what it prints.
