Why am I getting TypeError: 'module' object is not callable in python?

不打扰是莪最后的温柔 提交于 2019-12-14 02:43:21

问题


I'm creating a string that I an then use in a method that queries a mongodb collection. Eventually the dates will be from user input. Here's the relevant code and string:

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

The idea will be to use created_at_string as an argument in more complex query methods.

I'm getting:

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

Why?


回答1:


I've found your issue:

from datetime import datetime
import time
import datetime 

Let's look at this in order:

In your globals, you have something called datetime, a function. Then, you import time, a module object. Then, you import datetime, hence overwriting your datetime function. Here's an example:

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

No matter what, even if you change the order, you will overwrite something, be it the function or module objects. So, just rename something:

import datetime
import time
from datetime import datetime as dt


来源:https://stackoverflow.com/questions/30469445/why-am-i-getting-typeerror-module-object-is-not-callable-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!