Mit*_*ell 10 python nameerror python-2.7
以下是我正在处理的代码.据我所知,没有问题,但当我尝试运行这段代码时,我收到一个错误.
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
Run Code Online (Sandbox Code Playgroud)
错误如下:
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
Run Code Online (Sandbox Code Playgroud)
任何帮助,将不胜感激.
Pet*_*per 25
您已导入日期时间,但未定义timedelta.你想要:
from datetime import timedelta
Run Code Online (Sandbox Code Playgroud)
要么:
subtract = datetime.timedelta(hours=options.goback)
Run Code Online (Sandbox Code Playgroud)
此外,您的goback参数定义为字符串,但随后将其作为小时数传递给timedelta.您需要将其转换为整数,或者更好地type将选项中的参数设置为int.
| 归档时间: |
|
| 查看次数: |
22847 次 |
| 最近记录: |