Borislav Hadzhiev
Last updated: Apr 20, 2022
Photo from Unsplash
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.
Here is an example of how the error occurs.
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.
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.
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.
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.
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.
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.
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.