2014-11-22 47 views
-2

我想把日期October012000格式轉換爲python.I'm 2000年1月10日分享我的代碼here.Please改正我的錯誤......轉換October012000格式的2000年1月10日使用Python

代碼:

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 

但我發現了以下錯誤:

輸出:

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 
+0

嘗試在日期,月份和年份中封裝變量tr'功能。 (日期)+「/」+ str(month)+「/」+ str(year)' – gcarvelli 2014-11-22 05:31:07

+0

'Date = str(day)+「/」+ str(month)+ 「/」+ str(year)' – nu11p01n73R 2014-11-22 05:31:18

+0

[Python:TypeError:無法連接'str'和'int'對象]的可能重複(http://stackoverflow.com/questions/11844072/python-typeerror-cannot-concatenate- str-and-int-objects) – nu11p01n73R 2014-11-22 05:33:36

回答

2

的Python是一種強類型語言。這意味着您不能連接(使用+運營商)一個strint沒有第一投射(轉換式)intstr

在您創建{'January':1, 'February':2... etc的月份字典中,每個月都由int表示。這意味着當您查看十月份時,您將得到一個int(10)而不是str('10' - 注意引號)。這不起作用。

你至少需要:

# 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 

但你也可以重新編寫字典:

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} 
+0

感謝您的指導,我在重寫字典後得到了'01/10/2000'的輸出 – 2014-11-22 05:44:25

2

你幾乎正確的,但必須有monthDict像「一月」行情: '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; 
相關問題