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.
Code
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:00What 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
Age CalculatorCalculate exact age in years, months, and days between a birth date and a reference date, plus total days and the next birthday countdown.Business Days CalculatorCount the weekdays between two dates, excluding weekends and any holidays you list, and see how many calendar and weekend days are involved.Cron Next Runs CalculatorCompute the next scheduled run times for a standard five-field cron expression, supporting ranges, lists, steps, and day-of-week naming semantics.Duration HumanizerTurn a number of seconds into a readable duration such as 1 day, 2 hours, 3 minutes, and show the equivalent in minutes and hours.
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`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.