Skip to main content

How to Format a Date and Time as Text in Python with strftime

· 3 min read
Jagdish Kumawat
Founder @ Dewiride

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​

Syntax
<moment>.strftime(<format>)
PartWhat 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:

format_time.py
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"))

The format_time.py script in a macOS-style code window: a datetime for 28 November 2026, 13:36:55 UTC, printed with two strftime formats.

Step 2: Run It​

Terminal
uv run python format_time.py
Output
2026-11-28_13-36-55
28 November 2026, 13:36

The script's output in a terminal: 2026-11-28_13-36-55 and 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​

MistakeWhat happensDo this instead
%M for the month%M is the minute: "%Y-%M-%d" printed 2026-36-28Use %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 reservedUse - or _ between the parts

Troubleshooting​

SymptomLikely causeFix
A month number that's too big, or changes every minute%M where %m was meantUse %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​