Date Ordinal Output?
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 "1st"
, the number 2
, "2nd"
, et cetera, et cetera.
This is for working with dates in a breadcrumb trail
Home > Venues > Bar Academy > 2009 > April > 01
is what is currently shown
I'd like to have something along the lines of
Home > Venues > Bar Academy > 2009 > April > 1st
Or shorten David's answer with:
if 4 <= day <= 20 or 24 <= day <= 30:
suffix = "th"
else:
suffix = ["st", "nd", "rd"][day % 10 - 1]
Here's a more general solution:
def ordinal(n):
if 10 <= n % 100 < 20:
return str(n) + 'th'
else:
return str(n) + {1 : 'st', 2 : 'nd', 3 : 'rd'}.get(n % 10, "th")
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
These days I'd use Arrow http://arrow.readthedocs.io/en/latest/ (which definately wasn't around in '09)
>>> import arrow
>>> from datetime import datetime
>>> arrow.get(datetime.utcnow()).format('Do')
'27th'