基本Python编程使用字典将月号转换为月份名

时间:2013-01-26 03:57:09

标签: python python-2.7

我是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 个答案:

答案 0 :(得分:11)

使用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

答案 1 :(得分: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 

答案 2 :(得分:2)

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

答案 3 :(得分:1)

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

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

因此,日期[: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])]中的密钥,因为您使用整数作为字典键。但是你的输入(来自用户)是一个字符串,而不是整数。