-1

I am printing the current date using print(now.strftime("%d-%B-%Y")) which is working.

However, instead of it printing 21-November-2020, I want it to print the suffix for each day so 21st-November-2020 instead. As well, it should do this for each day automatically (2nd, 5th, 30th...). Is this possible?

Feel free to ask any questions.

asohasf1241
  • 195
  • 1
  • 10
  • 1
    Does this answer your question? [Date Ordinal Output?](https://stackoverflow.com/questions/739241/date-ordinal-output) – Hamza Nov 21 '20 at 03:04

1 Answers1

1
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('{S}-%B-%Y', dt.now()))

Out:

23rd-September-2022

Based on the day, it will auto return the correct suffix, e.g., 1st, 3rd, 10th.

joe hoeller
  • 1,248
  • 12
  • 22