加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python – Timedelta没有定义

发布时间:2020-12-16 23:40:15 所属栏目:Python 来源:网络整理
导读:下面是我正在处理的代码.从我可以告诉的没有问题,但是当我尝试运行这段代码时,我收到一个错误. import os import datetimedef parSEOptions(): import optparse parser = optparse.OptionParser(usage= '-h') parser.add_option('-t','--type', choices= ('
下面是我正在处理的代码.从我可以告诉的没有问题,但是当我尝试运行这段代码时,我收到一个错误.
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:Python27LibSITE-P~1PYTHON~2pywinframeworkscriptutils.py",line 325,in RunScript
    exec codeObject in __main__.__dict__
  File "C:UsersuserDesktopPythonpython.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.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读