Borislav Hadzhiev
Wed Apr 20 2022·2 min read
Photo by Maksim Istomin
The Python "TypeError: 'datetime.datetime' object is not subscriptable" occurs when we use square brackets to access an index or a key in a datetime object. To solve the error, use dot notation to access an attribute or remove the square brackets accessor.
Here is an example of how the error occurs.
from datetime import datetime result = datetime.today() print(type(result)) # 👉️ <class 'datetime.datetime'> # ⛔️ TypeError: 'datetime.datetime' object is not subscriptable print(result[0])
You could also be trying to access a specific key.
from datetime import datetime result = datetime.today() print(type(result)) # ⛔️ TypeError: 'datetime.datetime' object is not subscriptable print(result['some_key'])
Instead, you should access an attribute on the datetime object or remove the square brackets accessor.
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.
The "TypeError: object is not subscriptable" means that we are using square brackets to either access a key in a specific object or to access a specific index, however the object doesn't support this functionality.