将输入日期转换为字符串?

时间:2015-11-02 18:29:53

标签: python string date input

我想知道如何转换输入日期,例如,如果我输入01/01/1996,输出将是“1996年1月1日”,我需要能够为输入的任何日期执行此操作。 我需要使用切片。 提前谢谢。

inLine = input("please enter a date (dd/mm/yyyy) : ").split(',') 
 monthNames = ("January", "February", "March", \
             "April", "May", "June", \
              "July", "August", "September", \
          "October", "November", "December" ) 
month = inLine [:10]
month2 = "month"[:1]
day = inLine
year = inLine[0:2]
year2 = "year"[0:4]
print("this is the date %s %s %s." % (month2, day2, year2))

2 个答案:

答案 0 :(得分:2)

我不知道为什么在Python中已存在datetime parsing libraries时需要拆分输入。

>>> from datetime import datetime
>>> datetime.strptime('01/01/1996', '%M/%d/%Y').strftime('%d %B %Y')
'01 January 1996'

答案 1 :(得分:1)

这是非常简单的回应。您需要离开并了解数组,索引和操作它们。我还建议,如果这是某种类型的家庭作业,你会经历并做更多的例子,看看如果我输入无效的输入会发生什么。

inLine = input("please enter a date (dd/mm/yyyy) : ").split('/') 
monthNames = ("January", "February", "March", \
             "April", "May", "June", \
              "July", "August", "September", \
          "October", "November", "December" ) 
day = int(inLine[0])
month = int(inLine[1])
year = int(inLine[2])

print("this is the date %s %s %s." % (day, monthNames[month-1], year))