strftime không có directive cho suffix (st, nd, rd, th). Cần tự viết function thêm suffix.
Ví dụ
from datetime import datetime
now = datetime.now()
def suffix(day):
if 4 <= day <= 20 or 24 <= day <= 30:
return "th"
else:
return ["st", "nd", "rd"][day % 10 - 1]
my_date = now.strftime("%b %d" + suffix(now.day))
print(my_date)
Kết quả
Jan 15th
Cách khác: Format thủ công
day = now.day
suffix = "th" if 11 <= day <= 13 else {1:"st", 2:"nd", 3:"rd"}.get(day % 10, "th")
formatted = now.strftime(f"%b {day}{suffix}")