TypeError: 'datetime.datetime' object is not subscriptable

avatar

Borislav Hadzhiev

Wed Apr 20 20222 min read

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

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.

typeerror datetime datetime object is not subscriptable

Here is an example of how the error occurs.

main.py
from datetime import datetime result = datetime.today() print(type(result)) # 👉️ <class 'datetime.datetime'> # ⛔️ TypeError: 'datetime.datetime' object is not subscriptable print(result[0])
We are using square brackets to access an index on a datetime object, but datetime objects are not subscriptable.

You could also be trying to access a specific key.

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

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.

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.

Use the search field on my Home Page to filter through my more than 1,000 articles.