Reputation: 251
ex1)
date1 = datetime.date(2021, 1, 26)
date2 ='Tuesday, January 26th, 2021'
ex2)
date1 = datetime.date(2021, 2, 21)
date2 = 'Sunday, February 21st, 2021'
I want to change date1
to date2
. What should I do?
I tried this, but it didn't work out that 1's digits are 1,2,3 like datetime.date(2021, 2, 21),datetime.date(2021, 2, 2),datetime.date(2021, 2, 23)
date1 = strftime('%A, %B %dth, %Y')
Upvotes: 1
Views: 1287
Reputation: 25614
you're looking for the ordinal numeral. borrowing from Ordinal numbers replacement, you can use
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'
Upvotes: 5