Implementing @Frosty Snomwan's Method And An Expansion Of It
When I first tried to implement Frosty Snowman's outstanding answer, I misapplied it in my haste. His is the ord2 function below. My "not as good function" is ord1. He passes in a number. Mine takes a string. Both could be easily edited to receive different input types. I will be using his function, but I thought some codes might find the full "experimental" implementation of both helpful.
from datetime import datetime
def ord1(n):
if 4 <= int(n) <= 20 or int(n[-1]) >= 4 or int(n[-1]) == 0:
return f"{n}th"
elif int(n[-1]) == 1:
return f"{n}st"
elif int(n[-1]) == 2:
return f"{n}nd"
elif int(n[-1]) == 3:
return f"{n}rd"
def ord2(n):
return str(n) + (
"th" if 4 <= n % 100 <= 20 else {1: "st", 2: "nd", 3: "rd"}.get(n % 10, "th")
)
today = datetime.now()
date = today.strftime("%d")
date = ord2(int(date))
full_date_time = today.strftime(f"%A, {date} %B %Y %I:%M:%S %p")
print(full_date_time)
for date in range(1, 32, 1):
date_ord1 = ord1(str(date))
date_ord2 = ord2(date)
print(date_ord1, date_ord2)
Output is
Monday, 21st August 2023 01:33:11 PM
1st 1st
2nd 2nd
3rd 3rd
4th 4th
5th 5th
... all th's ...
20th 20th
21st 21st
22nd 22nd
23rd 23rd
24th 24th
... all th's ...
30th 30th
31st 31st
I final functional form that might be more overall useful would be ...
def format_date_time(a_date_time):
date = a_date_time.strftime("%d")
d = int(date)
date = date + (
"th" if 4 <= d % 100 <= 20 else {1: "st", 2: "nd", 3: "rd"}.get(d % 10, "th")
)
full_date_time = a_date_time.strftime(f"%A, {date} %B %Y %I:%M:%S %p")
return full_date_time