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


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

Updated on: 12-Jun-2020

952 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements