How do I display the date, like "Aug 5th", using Python's strftime?

PythonServer Side ProgrammingProgramming

It is not possible to get a suffix like st, nd, rd and th using the strftime function. The strftime function doesn't have a directive that supports this formatting. You can create your own function to figure out the suffix and add it to the formatting string you provide.

Example

from datetime import datetime
now = datetime.now()
def suffix(day):
  suffix = ""
  if 4 <= day <= 20 or 24 <= day <= 30:
    suffix = "th"
  else:
    suffix = ["st", "nd", "rd"][day % 10 - 1]
  return suffix
my_date = now.strftime("%b %d" + suffix(now.day))
print(my_date)

Output

This will give the output −

Jan 15th
raja
Published on 08-Jan-2018 10:11:18
Advertisements