-2

I want to convert the date October012000 format to 01/10/2000 in python.I'm sharing my code here.Please correct my mistake......

Code:

date=October012000
day=date2[-6:-4]
year=date2[-4:]
month=date2[0:-6]
print year,day,month
monthDict = {'January':1, 'February':2, 'March':3, 'April':4, 'May':5, 'June':6, 
                            'July':7, 'August':8, 'September':9, 'October':10, 'November':11, 'December':12}
month = monthDict[month]
Date=day+"/"+month+"/"+year

But i'm getting the following error:

Output:

TypeError                                 Traceback (most recent call last)
<ipython-input-23-42dbf62e7bab> in <module>()
      3 #month1=str(month)
      4 #day
----> 5 Date=day+"/"+month+"/"+year

TypeError: cannot concatenate 'str' and 'int' objects
  • Try encapsulating the day, month, and year variables in the `str` function. The last line would look like `Date = str(day) + "/" + str(month) + "/" + str(year)` – gcarvelli Nov 22 '14 at 05:31
  • `Date=str(day)+"/"+str(month)+"/"+str(year)` – nu11p01n73R Nov 22 '14 at 05:31
  • possible duplicate of [Python: TypeError: cannot concatenate 'str' and 'int' objects](http://stackoverflow.com/questions/11844072/python-typeerror-cannot-concatenate-str-and-int-objects) – nu11p01n73R Nov 22 '14 at 05:33

2 Answers2

2

Python is a strongly typed language. This means that you can't concatenate (use the + operator) a str and an int without first casting (converting a type) the int to a str.

In the dictionary of months you created {'January':1, 'February':2... etc, you have each of the months represented by an int. This means when you look up October, you are getting an int (10) instead of a str ('10' – notice the quotes). This will not work.

At a minimum you need:

# note: since day and year are both substrings of october012000, they already are str's
#       and do not have to be cast to be concatenated.
date=day+"/"+str(month)+"/"+year

But you could also re-write the dict:

monthDict = {'January':'1', 'February':'2', 'March':'3', 'April':'4', 'May':'5', 
             'June':'6', 'July':’7’, 'August':'8', 'September':'9', 'October':'10', 
             'November':'11', 'December':12}
cwallenpoole
  • 79,954
  • 26
  • 128
  • 166
2

You almost right but there must be quotes in monthDict like 'January':'1'

date2 ="October012000"
#print "length of date ",len(date2);

day=date2[-6:-4]
year=date2[-4:]
month=date2[0:-6]
print year,day,month

monthDict ={'January':'1','February':'2','March':'3','April':'4','May':'5','June':'6','July':'7','August':'8','September':'9','October':'10','November':'11','December':'12'}
month = monthDict[month]

Date=day+"/"+month+"/"+year
print Date;
Mohamed Jaleel Nazir
  • 5,776
  • 3
  • 34
  • 48