Timedelta is not defined

Below is the code I am working on. From what I can tell there is no issue, but when I attempt to run the piece of code I receive an error.

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

Error is as followed:

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

Any help would be appreciated.

Answers


You've imported datetime, but not defined timedelta. You want either:

from datetime import timedelta

or:

subtract = datetime.timedelta(hours=options.goback)

Also, your goback parameter is defined as a string, but then you pass it to timedelta as the number of hours. You'll need to convert it to an integer, or better still set the type argument in your option to int instead.


Where you have timedelta, you need to put datetime. before it, so it's actually datetime.timedelta


It should be datetime.timedelta


I find this problem may occur in some of my sutpid action. I create a file named datetime.py and even I rename the file, I still leave the datetime.pyc in the folder... So every file that import dateime will use this file and timedelta cannot be found. After I delete the file:datetime.pyc, It works.


Need Your Help

jQuery / Dojo - How do I use jQuery with Dojo toolkit

javascript jquery dojo

How do I use jQuery with Dojo toolkit? I've heard of both libraries being used simultaneously, jQuery for DOM-related and Dojo for UI (dijit), but I can't find any tutorials or examples of this. W...

Redirect to referer url in codeigniter

php codeigniter http-referer

In messaging system of my project when you get a message from a user you a email alert saying that the another user has sent a message to view the message click here (i.e the url of message) So if ...