如何使用 Python 的 strftime 显示日期,如"8 月 5 日"?

pythonserver side programmingprogramming更新于 2026/2/6 21:32:17

使用 strftime 函数无法获取 st、nd、rd 和 th 等后缀。strftime 函数没有支持此格式的指令。您可以创建自己的函数来找出后缀并将其添加到您提供的格式字符串中。

示例

from datetime import datetime
now = datetime.now()
def suffix(day):
  suffix = ""
  if 4 <= day <= 20 or 24 <= day <= 30:
    suffix = "th"
  else:
    suffix = ["st", "nd", "rd"][day % 10 - 1]
  return suffix
my_date = now.strftime("%b %d" + suffix(now.day))
print(my_date)

输出

这将给出输出 −

Jan 15th

相关文章


有用资源