4

我是python新手,只知道最基本的级别。我应该允许以 dd/mm/yyyy 的形式输入日期并将其转换为 1986 年 8 月 26 日之类的内容。我不知道如何将月份(mm)从数字转换为单词。下面是我目前的代码,希望你能帮助我。** 请不要建议使用日历功能,我们应该使用 dict 来解决这个问题。

谢谢 (:

#allow the user to input the date
date=raw_input("Please enter the date in the format of dd/mm/year: ")

#split the strings
date=date.split('/')

#day
day=date[:2]

#create a dictionary for the months
monthDict={1:'Jan', 2:'Feb', 3:'Mar', 4:'Apr', 5:'May', 6:'Jun', 7:'Jul', 8:'Aug', 9:'Sep', 10:'Oct', 11:'Nov', 12:'Dec'}
#month
month=date[3:5]
if month in monthDict:
    for key,value in monthDict:
        month=value

#year
year=date[4:]

#print the result in the required format
print day, month, "," , year 
4

4 回答 4

12

使用 Python 的 datetime.datetime!阅读使用my_date = strptime(the_string, "%d/%m/%Y"). 使用 打印my_date.strftime("%d %b, %Y")

访问:http ://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior

例子:

import datetime
input = '23/12/2011'
my_date = datetime.datetime.strptime(input, "%d/%m/%Y")
print my_date.strftime("%d %b, %Y") # 23 Dec, 2011
于 2013-01-26T05:08:42.137 回答
3
date = raw_input("Please enter the date in the format of dd/mm/year: ")
date = date.split('/')
day = date[0] # date is, for example, [1,2,1998]. A list, because you have use split()
monthDict = {1:'Jan', 2:'Feb', 3:'Mar', 4:'Apr', 5:'May', 6:'Jun', 
            7:'Jul', 8:'Aug', 9:'Sep', 10:'Oct', 11:'Nov', 12:'Dec'}
month = date[1] # Notice how I have changed this as well
                # because the length of date is only 3
month = monthDict[int(month)]
year = date[2] # Also changed this, otherwise it would be an IndexError
print day, month, "," , year

运行时:

Please enter the date in the format of dd/mm/year: 1/5/2004
1 May , 2004
于 2013-01-26T04:15:23.733 回答
2

完成拆分后,您不需要使用像 day=date[:2] 这样的索引。只需使用say = date[0]。同样,不需要循环来匹配字典值。你可以看到下面的代码。

#allow the user to input the date
date=raw_input("Please enter the date in the format of dd/mm/year: ")

#split the strings
date=date.split('/')

#day
day=date[0]

#create a dictionary for the months
monthDict={1:'Jan', 2:'Feb', 3:'Mar', 4:'Apr', 5:'May', 6:'Jun', 7:'Jul', 8:'Aug', 9:'Sep', 10:'Oct', 11:'Nov', 12:'Dec'}
#month
monthIndex= int(date[1])

month = monthDict[monthIndex]
#year
year=date[2]
print day, month, "," , year 
于 2013-01-26T04:13:16.020 回答
1

拆分日期字符串时,您将只有三个元素(0、1 和 2):

>>> date=date.split('/')
>>> print date
['11', '12', '2012']
  ^     ^     ^
  0     1     2

因此, date[:2] 将等于:

>>> day=date[:2] # that is, date up to (but not including) position 2
>>> print day
['11', '12']

而且date[4]不会存在,也不会存在date[3:5]

此外,您需要像这样调用您的字典值:

>>> print monthDict[12]
Dec

因此,要打印日、月、年的组合,您需要这样做:

>>> print date[0], monthDict[int(date[1])] + ", " + date[2]
11 Dec, 2012

您必须使用int(date[0])作为您的键,monthDict[int(date[0])]因为您使用整数作为您的字典键。但是您的输入(来自用户)是一个字符串,而不是整数。

于 2013-01-26T04:06:11.633 回答