下面是我正在处理的代码.从我可以告诉的没有问题,但是当我尝试运行这段代码时,我收到一个错误.
import os
import datetime
def parSEOptions():
import optparse
parser = optparse.OptionParser(usage= '-h')
parser.add_option('-t','--type',\
choices= ('Warning','Error','Information','All'),\
help= 'The type of error',default= 'Warning')
parser.add_option('-g','--goback',\
type= 'string')
(options,args) = parser.parse_args()
return options
options = parSEOptions() now = datetime.datetime.now() subtract = timedelta(hours=options.goback) difference = now - subtract
if options.type=='All' and options.goback==24:
os.startfile('logfile.htm')
else:
print
print 'Type =',options.type,print
print 'Go Back =',options.goback,'hours'
print difference.strftime("%H:%M:%S %a,%B %d %Y")
print
错误如下:
Traceback (most recent call last):
File "C:\Python27\Lib\SITE-P~1\PYTHON~2\pywin\framework\scriptutils.py",line 325,in RunScript
exec codeObject in __main__.__dict__
File "C:\Users\user\Desktop\Python\python.py",line 19,in <module>
subtract = timedelta(hours=options.goback)
NameError: name 'timedelta' is not defined
任何帮助将不胜感激.
解决方法
您已导入datetime,但未定义timedelta.你想要:
from datetime import timedelta
要么:
subtract = datetime.timedelta(hours=options.goback)
此外,您的goback参数被定义为一个字符串,但是您将其传递给timedelta作为小时数.您需要将其转换为整数,或者更好地仍然将您的选项中的type参数设置为int.
