使用 strftime 更改为字符串时如何将 datetime.date 更改为 st、nd、rd、th

How to change datetime.date to st,nd,rd,th when changing to string using strftime

ex1)
date1 = datetime.date(2021, 1, 26)
date2 ='Tuesday, January 26th, 2021'

ex2)
date1 = datetime.date(2021, 2, 21)
date2 = 'Sunday, February 21st, 2021'

我想将 date1 更改为 date2。我该怎么办?

我试过了,但是没有成功 1 的数字是 1,2,3 就像 datetime.date(2021, 2, 21),datetime.date(2021, 2, 2 ),datetime.date(2021, 2, 23)

date1 = strftime('%A, %B %dth, %Y')

您正在寻找ordinal numeral. borrowing from Ordinal numbers replacement,您可以使用

import datetime

def ordinal(n: int) -> str:
    """
    derive the ordinal numeral for a given number n
    """
    return f"{n:d}{'tsnrhtdd'[(n//10%10!=1)*(n%10<4)*n%10::4]}"

date1 = datetime.date(2021, 1, 26)

dayOrdinal = ordinal(date1.day)

date1_string = date1.strftime(f'%A, %B {dayOrdinal}, %Y')
# 'Tuesday, January 26th, 2021'