Display the date, like "May 5th", using pythons strftime?

Buttons840 picture Buttons840 · May 5, 2011 · Viewed 26.7k times · Source

Possible Duplicate:
Python: Date Ordinal Output?

In Python time.strftime can produce output like "Thursday May 05" easily enough, but I would like to generate a string like "Thursday May 5th" (notice the additional "th" on the date). What is the best way to do this?

Answer

Acorn picture Acorn · May 5, 2011

strftime doesn't allow you to format a date with a suffix.

Here's a way to get the correct suffix:

if 4 <= day <= 20 or 24 <= day <= 30:
    suffix = "th"
else:
    suffix = ["st", "nd", "rd"][day % 10 - 1]

found here

Update:

Combining a more compact solution based on Jochen's comment with gsteff's answer:

from datetime import datetime as dt

def suffix(d):
    return 'th' if 11<=d<=13 else {1:'st',2:'nd',3:'rd'}.get(d%10, 'th')

def custom_strftime(format, t):
    return t.strftime(format).replace('{S}', str(t.day) + suffix(t.day))

print custom_strftime('%B {S}, %Y', dt.now())

Gives:

May 5th, 2011