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

使用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