-2

Hi I need to get system date as below format in python

14th May 2021
31st December 2020
3rd April 2020

Appreciate any help.

AMC
  • 2,642
  • 7
  • 13
  • 35
  • 4
    Does this answer your question? [Display the date, like "May 5th", using pythons strftime?](https://stackoverflow.com/questions/5891555/display-the-date-like-may-5th-using-pythons-strftime) – sandertjuh May 14 '21 at 15:28
  • Please see [ask], [help/on-topic]. – AMC May 14 '21 at 15:31

2 Answers2

1

You need to use strftime function from the datetime module.

from datetime import date
mydate = date(2021, 5, 14) #14th May 2021
mydate.strftime('%d %b %Y')

However this doesn't get you the th suffix. For that you have to make a custom function.

from datetime import datetime as dt,date

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',  date(2021, 5, 14)))

Which will print

14th May 2021
kinshukdua
  • 1,944
  • 1
  • 5
  • 15
0

I suggest you use time and format as below.

import time
day = time.strftime('%d')
day_endings = {
    1: 'st',
    2: 'nd',
    3: 'rd',
    21: 'st',
    22: 'nd',
    23: 'rd',
    31: 'st'
}
if day not in day_endings.keys():
    print(time.strftime('%dth %b %Y'))
else:
    print(print(time.strftime(f'%d{day_endings[day]} %b %Y'))
    
    

output

14th May, 2021

Second test with ending in dict

import time
day = 1

day_endings = {
    1: 'st',
    2: 'nd',
    3: 'rd',
    21: 'st',
    22: 'nd',
    23: 'rd',
    31: 'st'
}
if day not in day_endings.keys():
    print('wa')
    print(time.strftime('%dth %b %Y'))
else:
    print(time.strftime(f'1{day_endings[day]} %b %Y'))
    

1st May 2021

Buddy Bob
  • 5,829
  • 1
  • 13
  • 44