I\'m wondering if there is a quick and easy way to output ordinals given a number in python.
For example, given the number 1
, I\'d like to output
Not sure if it existed 5 years ago when you asked this question, but the inflect package has a function to do what you're looking for:
>>> import inflect
>>> p = inflect.engine()
>>> for i in range(1,32):
... print p.ordinal(i)
...
1st
2nd
3rd
4th
5th
6th
7th
8th
9th
10th
11th
12th
13th
14th
15th
16th
17th
18th
19th
20th
21st
22nd
23rd
24th
25th
26th
27th
28th
29th
30th
31st
I made a function that seems to work in this case. Just pass in a date object, and it will use the day to figure out the suffix. Hope it helps
from datetime import date
def get_day_ordinal(d):
sDay = '%dth'
if d.day <= 10 or d.day >= 21:
sDay = '%dst' if d.day % 10 == 1 else sDay
sDay = '%dnd' if d.day % 10 == 2 else sDay
sDay = '%drd' if d.day % 10 == 3 else sDay
return sDay % d.day
d = date.today()
print get_day_ordinal(d)