以下是我正在處理的代碼。從我可以告訴的沒有問題,但是當我嘗試運行這段代碼時,我收到一個錯誤。Timedelta未定義
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' 和我已經改變類型爲int。再次感謝你。 – Mitchell
是的,一旦你通過'datetime.timedelta'引用了timedelta類的日期時間就是通常的最佳實踐。關鍵是導入日期時間模塊可以獲得它定義的所有名稱,但是您必須通過名稱空間引用它們。您將看到導入模塊的一般模式,然後經常引用其內容。 –