Hi I need to get system date as below format in python
14th May 2021
31st December 2020
3rd April 2020
Appreciate any help.
Hi I need to get system date as below format in python
14th May 2021
31st December 2020
3rd April 2020
Appreciate any help.
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
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