【问题标题】:Converting the format of a date string [duplicate]转换日期字符串的格式[重复]
【发布时间】:2017-05-18 14:39:24
【问题描述】:

我有这段代码可以获取当前日期并将其转换为文字格式。

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 的用户输入转换为 word 格式?

【问题讨论】:

  • 使用正确格式的datetime.strptime。请参阅文档。

标签: python python-3.x datetime datetime-format python-datetime


【解决方案1】:

你可以的,

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)]))

【讨论】:

  • 谢谢,但这只是按原样返回日期,我希望它像 1 月 4 日星期三一样返回
  • 在此之后,您可以按照自己的登录方式获取星期几、日期、月份...等,并按照您已经在做的方式显示它
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-06-16
相关资源
最近更新 更多