我对Python很新,所以希望我遇到的问题有一个简单的解决方案。Python datetime TypeError,整数预期
在工作中,我们总是使用Shell(ksh)或Perl来处理所有脚本工作。由于Python已经与Solaris一起交付了一段时间,它已经(最终)被作为脚本平台的绿灯。我已经开始使用Python对我们的脚本进行原型改进。
我想要完成的是采取时间戳和字符串表示时间戳并为某些日期算术创建日期时间对象。
我的示例代码如下:
#!/bin/python
import datetime
fileTime="201009211100"
format = "YYYYmmdd"
yIdxS = format.find('Y')
yIdxE = format.rfind('Y')
if not fileTime[yIdxS:yIdxE+1].isdigit():
print "ERROR: Year in wrong format"
exit
else:
print "Year [" + fileTime[yIdxS:yIdxE+1] + "]"
mIdxS = format.find('m')
mIdxE = format.rfind('m')
if not fileTime[mIdxS:mIdxE+1].isdigit():
print "ERROR: Month in wrong format"
exit
else:
print "Month [" + fileTime[mIdxS:mIdxE+1] + "]"
dIdxS = format.find('d')
dIdxE = format.rfind('d')
if not fileTime[dIdxS:dIdxE+1].isdigit():
print "ERROR: Day in wrong format"
exit
else:
print "Day [" + fileTime[dIdxS:dIdxE+1] + "]"
old = datetime.date(fileTime[yIdxS:yIdxE+1], \
fileTime[mIdxS:mIdxE+1], \
fileTime[dIdxS:dIdxE+1]);
我得到以下输出/错误:
Year [2010]
Month [09]
Day [21]
Traceback (most recent call last):
File "./example.py", line 37, in <module>
fileTime[dIdxS:dIdxE+1]);
TypeError: an integer is required
我不明白为什么我得到这个TypeError异常。我对Python的动态类型的理解是,如果字符串都是数字,我不需要将字符串转换为整数。
所以这个问题似乎是我要么缺少我需要的东西,要么我对语言的理解是有缺陷的。
任何帮助将不胜感激。谢谢。
一个小常用约定:在第一行使用'#!/ usr/bin/env python'。看[这个问题](http://stackoverflow.com/questions/2429511/why-do-people-write-usr-bin-env-python-on-the-first-line-of-a-python-script) 。 – snapshoe 2010-09-30 02:38:22