TypeError: 'datetime.datetime' object is not callable

avatar

Borislav Hadzhiev

Last updated: Apr 20, 2022

banner

Photo from Unsplash

TypeError: 'datetime.datetime' object is not callable #

The Python "TypeError: 'datetime.datetime' object is not callable" occurs when we override a built-in class or method from the datetime module. To solve the error, resolve any clashes in names between your variables and the built-in classes.

typeerror datetime datetime object is not callable

Here is an example of how the error occurs.

main.py
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)

We shadowed the built-in date class by setting it to a datetime object and tried to call it as a function.

However, now the date variable stores a datetime object, and not the built-in class.

To solve the error, make sure to not override any of the built-in methods and classes from the datetime module.

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

Renaming the variable should resolve the issue.

Another common cause of the error is trying to call a datetime object as if it were a function.

main.py
from datetime import datetime my_date = datetime.today() # ⛔️ TypeError: 'datetime.datetime' object is not callable my_date() # 👈️ remove extra set of parenthesis

To solve the error, we have to either figure out how the variable got assigned a datetime object instead of a function or class or remove the extra set of parenthesis.

main.py
from datetime import datetime, date my_date = datetime.today() print(my_date) # 👉️ "2022-05-21 10:54:20.229918"

You could be trying to call a datetime object by mistake when you mean to access an attribute on the 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 wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.