Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Basic Python Programming to convert month number to month name using dictionary

I am new to python and only know the most basic level. I am supposed to allow input of a date in the form of dd/mm/yyyy and convert it to something like 26 Aug, 1986. I am stuck as to how to convert my month(mm) from numbers to words. Below is my current code, hope you can help me. ** please do not suggest using calendar function, we are supposed to use dict to solve this question.

Thank you (:

#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 
like image 419
Lavinia Avatar asked Dec 01 '22 20:12

Lavinia


2 Answers

Use Python's datetime.datetime! Read using my_date = strptime(the_string, "%d/%m/%Y"). Print it using my_date.strftime("%d %b, %Y").

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

Example:

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
like image 90
Escualo Avatar answered Dec 16 '22 12:12

Escualo


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

When run:

Please enter the date in the format of dd/mm/year: 1/5/2004
1 May , 2004
like image 40
TerryA Avatar answered Dec 16 '22 10:12

TerryA