为什么我得到TypeError:'module'对象在python中不可调用?

dws*_*ein 1 python mongodb pymongo python-2.7

我正在创建一个字符串,然后我在一个查询mongodb集合的方法中使用它.最终日期将来自用户输入.这是相关的代码和字符串:

import pymongo
from pymongo import MongoClient
from datetime import datetime
import time
import datetime
start_yr    = 2015
start_mnth  = 2
start_day   = 1
end_yr      = 2015
end_mnth    = 2
end_day     = 28

# this is the line called in the error
created_at_string = { "created_at": {"$gte" : datetime(start_yr, start_mnth, start_day),"$lt" : datetime(end_yr, end_mnth, end_day)}}
Run Code Online (Sandbox Code Playgroud)

这个想法将created_at_string用作更复杂的查询方法中的参数.

我越来越:

Traceback (most recent call last):
  File "main.py", line 218, in <module>
    program.runProgram()
  File "main.py", line 61, in runProgram
    report.RcreateReport()
  File "/filepath/report.py", line 95, in RcreateReport
 created_at_string = { "created_at": {"$gte" : datetime(start_yr, start_mnth, start_day),"$lt" : datetime(end_yr, end_mnth, end_day)}}
TypeError: 'module' object is not callable
Run Code Online (Sandbox Code Playgroud)

为什么?

Ziz*_*212 5

我找到了你的问题:

from datetime import datetime
import time
import datetime 
Run Code Online (Sandbox Code Playgroud)

我们按顺序看看这个:

在你的globals,你有一个叫做datetime函数的东西.然后,导入time一个模块对象.然后,导入datetime,从而覆盖您的datetime功能.这是一个例子:

>>> from datetime import datetime
>>> datetime(2015, 05, 26)
datetime.datetime(2015, 5, 26, 0, 0)
>>> import datetime
>>> datetime(2015, 05, 26)

Traceback (most recent call last):
  File "<pyshell#24>", line 1, in <module>
    datetime(2015, 05, 26)
TypeError: 'module' object is not callable
>>> 
Run Code Online (Sandbox Code Playgroud)

无论如何,即使你改变了顺序,你也会覆盖某些东西,无论是函数还是模块对象.所以,只需重命名:

import datetime
import time
from datetime import datetime as dt
Run Code Online (Sandbox Code Playgroud)