类型错误:’datetime.datetime’ 对象不可调用 [修复]

TypeError: ‘datetime.datetime’ 对象不可调用

TypeError: ‘datetime.datetime’ object is not callable

当我们覆盖模块中的内置类或方法时,会出现 Python“TypeError: ‘datetime.datetime’ object is not callable” datetime

要解决该错误,请解决变量和内置类之间的名称冲突。

类型错误日期时间日期时间对象不可调用

错误地覆盖了内置的 date() 类

下面是错误如何发生的示例。

主程序
from datetime import datetime, date # 👇️ override built-in date() class by mistake date = datetime.today() result = date(2022, 9, 24) # ⛔️ TypeError: 'datetime.datetime' object is not callable print(result)

date我们通过将内置类设置为datetime对象来隐藏内置类,并尝试将其作为函数调用。

但是,现在date变量存储的是datetime 对象而不是内置类。

重命名变量以解决错误

要解决该错误,请确保不要覆盖模块中的任何内置方法和类datetime

主程序
from datetime import datetime, date # ✅ Renamed variable my_date = datetime.today() result = date(2022, 9, 24) print(result) # 👉️ "2022-09-24"

我们给变量起了一个不同的名字,所以它不再与内置
date类冲突。

尝试将datetime对象作为函数调用

错误的另一个常见原因是试图datetime像调用函数一样调用对象。

主程序
from datetime import datetime my_date = datetime.today() # ⛔️ TypeError: 'datetime.datetime' object is not callable my_date() # 👈️ remove extra set of parentheses

要解决这个错误,要么弄清楚变量是如何被分配一个datetime
对象而不是一个函数或一个类,要么删除额外的一组括号。

主程序
from datetime import datetime, date my_date = datetime.today() print(my_date) # 👉️ "2023-01-31 18:53:59.264253"

删除额外的一组括号可以让我们毫无问题地打印日期。

You could be trying to call a datetime object by mistake when you meant to
access an attribute on the object.

If you need to access an attribute, use dot notation without parentheses.

main.py
from datetime import datetime, date my_date = datetime.today() print(my_date) # 👉️ "2023-01-31 18:53:59.264253" print(my_date.day) # 👉️ 31 print(my_date.hour) # 👉️ 18

Notice that we don’t use parentheses () when accessing attributes on an
object.

The best way to start debugging is to call the dir() function passing it the
imported module.

main.py
from datetime import datetime # 👇️ [...'astimezone', 'combine', 'ctime', 'date', 'day', # 'dst', 'fold', 'fromisocalendar', 'fromisoformat', # 'fromordinal', 'fromtimestamp', 'hour', 'isocalendar',... ] print(dir(datetime))

If you pass a module object to the
dir() function, it returns a list of
names of the module’s attributes.

You can use dot notation to access any of the attributes a datetime object
supports.

main.py
from datetime import datetime d = datetime(2022, 11, 24, 9, 30, 0) # 👇️ 24/11/22 print(d.strftime("%d/%m/%y")) print(d.year) # 👉️ 2022 print(d.month) # 👉️ 11

Or you can remove the square brackets if you didn’t intend to access an
attribute.

I’ve also written an article on
how to check if a variable is a Datetime object.

# Additional Resources

You can learn more about the related topics by checking out the following
tutorials: