2014-11-22 69 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; 
相关问题