python format datetime with "st", "nd", "rd", "th" (english ordinal suffix) like PHP's "S"

The django.utils.dateformat has a function format that takes two arguments, the first one being the date (a datetime.date [[or datetime.datetime]] instance, where datetime is the module in Python's standard library), the second one being the format string, and returns the resulting formatted string. The uppercase-S format item (if part of the format string, of course) is the one that expands to the proper one of 'st', 'nd', 'rd' or 'th', depending on the day-of-month of the date in question.


dont know about built in but I used this...

def ord(n):
    return str(n)+("th" if 4<=n%100<=20 else {1:"st",2:"nd",3:"rd"}.get(n%10, "th"))

and:

def dtStylish(dt,f):
    return dt.strftime(f).replace("{th}", ord(dt.day))

dtStylish can be called as follows to get Thu the 2nd at 4:30. Use {th} where you want to put the day of the month ("%d" python format code)

dtStylish(datetime(2019, 5, 2, 16, 30), '%a the {th} at %I:%M')

You can do this simply by using the humanize library

from django.contrib.humanize.templatetags.humanize import ordinal

You can then just give ordinal any integer, ie

ordinal(2) will return 2nd