Converting the format of a date string

806 views Asked by At

I have this code which gets the current date and converts it to word format.

import datetime

days={'0':'Monday','1':'Tuesday','2':'Wednesday',
      '3':'Thursday','4':'Friday','5':'Saturday',
      '6':'Sunday'}

months={'1':'January','2':'February','3':'March','4':'April',
        '5':'May','6':'June','7':'July','8':'August',
        '9':'September','10':'October','11':'November','12':'December'}

currentDay=datetime.date.weekday(datetime.datetime.now())
currentMonth=datetime.date.today().month
currentDate=str(datetime.date.today().day)
if currentDate[:1]=="1":suffix="st"
elif currentDate[:1]=="2":suffix="nd"
elif currentDate[:1]=="2":suffix="rd"
else:suffix="th"
dateString=("{} the {}{} of {}".format(
    days[str(currentDay)],currentDate,suffix,months[str(currentMonth)]))

output for today,

>>>Wednesday the 4th of January

how would I about turning a user input in the format DD/MM/YYYY to the word format?

1

There are 1 answers

2
Joshi Sravan Kumar On

You can do,

from datetime import datetime
user_input = "DD/MM/YYYY"
datetime_object = datetime.strptime(user_input, "%d/%m/%Y")

Followed by your logic

currentDay=datetime_object.weekday()
currentMonth=datetime_object.month
currentDate=str(datetime_object.day)
if currentDate[:1]=="1":suffix="st"
elif currentDate[:1]=="2":suffix="nd"
elif currentDate[:1]=="2":suffix="rd"
else:suffix="th"
dateString=("{} the {}{} of {}".format(
    days[str(currentDay)],currentDate,suffix,months[str(currentMonth)]))