我有这段代码获取当前日期并将其转换为字格式。
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)]))
今天的输出,
>>>Wednesday the 4th of January
我如何将DD/MM/YYYY
格式的用户输入转换为字格式?
答案 0 :(得分:0)
你可以,
from datetime import datetime
user_input = "DD/MM/YYYY"
datetime_object = datetime.strptime(user_input, "%d/%m/%Y")
遵循您的逻辑
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)]))