strftime Renders Dates With Format Codes

Render datetimes with strftime format codes — %Y %m %d %H %M %S for fields, %f for microseconds — and round-trip the output through strptime.

PythonCli Tooling

Code

pythonsnippet
18 lines
from datetime import datetime

stamp = datetime(2026, 11, 23, 9, 30, 5)

# strftime 按格式码渲染:ISO 与人类可读两种口径
print(stamp.strftime("%Y-%m-%dT%H:%M:%S"))
print(stamp.strftime("%Y年%m月%d日 %H:%M"))

# 星期与月份名称依赖本地化,%A 默认英文
print(stamp.strftime("%A"), stamp.strftime("%b"))

# %f 微秒:纳秒精度日志常用
utc = stamp.strftime("%Y-%m-%d %H:%M:%S.%f")
print(utc)

# round trip: strftime 的输出交给 strptime 还原
text = stamp.strftime("%d/%m/%Y %H:%M")
print(datetime.strptime(text, "%d/%m/%Y %H:%M"))

Output

Captured from a sandboxed run of this snippet in the build pipeline.

2026-11-23T09:30:05
2026年11月23日 09:30
Monday Nov
2026-11-23 09:30:05.000000
2026-11-23 09:30:00

What the code does

Demo state sits in top-level bindings: stamp, utc, text.

stamp.strftime("%Y-%m-%dT%H:%M:%S") renders 2026-11-23T09:30:05 and the %Y年%m月%d日 variant shows format codes mixing freely with literal characters. %A/%b produce the locale-default English weekday and month names, %f appends six-digit microseconds, and the last lines round-trip: text = stamp.strftime("%d/%m/%Y %H:%M") feeds datetime.strptime(text, "%d/%m/%Y %H:%M"), which reconstructs the original datetime.

Watch out for

  • Every symbol it touches is a language built-in — nothing to fetch.

Interactive Tools for This Topic

FAQ

Does this require external packages?
No. It relies only on built-in language and platform APIs, so you can paste it into a project without installing anything. Every import resolves inside the standard library — `datetime`. Its state lives in module-level bindings: `stamp`, `utc`, `text`.