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

时间:2015-05-26 21:42:27

标签: python mongodb python-2.7 pymongo

我正在创建一个字符串,然后我在查询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)}}

我们的想法是在更复杂的查询方法中使用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

为什么?

1 个答案:

答案 0 :(得分:5)

我找到了你的问题:

from datetime import datetime
import time
import datetime 

让我们按顺序看一下:

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
>>> 

无论如何,即使您更改了顺序,也会覆盖某些内容,无论是函数还是模块对象。所以,只需重命名:

import datetime
import time
from datetime import datetime as dt