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

更新於: 2020 年 6 月 12 日

1 千多瀏覽量

開啟你的職業生涯

完成課程並獲得認證

立即開始
廣告
© . All rights reserved.