TypeError: 'datetime.datetime' object is not subscriptable

avatar
Borislav Hadzhiev

Last updated: Apr 8, 2024
4 min

banner

# Table of Contents

  1. TypeError: 'datetime.datetime' object is not subscriptable
  2. TypeError: 'datetime.datetime' object is not iterable

# 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'])

# Access an attribute on the datetime object

Instead, you should access an attribute on the datetime object or remove the square brackets accessor.

You can access an attribute using dot notation.

main.py
from datetime import datetime result = datetime.today() print(result.date()) # ๐Ÿ‘‰๏ธ 2023-07-22

access attribute on the datetime 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 of a datetime object.

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

using dot notation to access any of the attributes of datetime object

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

# Datetime objects are not subscriptable

The error means that we are using square brackets to access a key in a specific object or to access a specific index, however, the object doesn't support this functionality.

You should only use square brackets to access subscriptable objects.

The subscriptable objects in Python are:

  • list
  • tuple
  • dictionary
  • string

All other objects have to be converted to a subscriptable object by using the list(), tuple(), dict() or str() classes to be able to use bracket notation.

Subscriptable objects implement the __getitem__ method whereas non-subscriptable objects do not.

main.py
a_list = ['bobby', 'hadz', 'com'] # ๐Ÿ‘‡๏ธ <built-in method __getitem__ of list object at 0x7f71f3252640> print(a_list.__getitem__)

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

The Python "TypeError: 'datetime.datetime' object is not iterable" occurs when we try to iterate over a datetime object instead of an iterable (e.g. a list).

To solve the error, track down where the variable got assigned a datetime object and correct the assignment.

typeerror datetime datetime object is not iterable

Here is an example of how the error occurs.

main.py
from datetime import datetime result = datetime.today() print(result) # ๐Ÿ‘‰๏ธ 2023-01-31 15:23:10.461035 # โ›”๏ธ TypeError: 'datetime.datetime' object is not iterable for i in result: print(i)

We are trying to iterate over a datetime object, but datetime objects are not iterable.

# Track down where the variable got assigned a datetime object

You have to figure out how the value got assigned a datetime object and correct the assignment to an iterable such as a list, string, tuple, etc.

Make sure you aren't reassigning an iterable to a datetime object somewhere by mistake.

main.py
from datetime import datetime my_list = ['bobby', 'hadz', 'com'] my_list = datetime.today() # # โ›”๏ธ TypeError: 'datetime.datetime' object is not iterable for i in my_list: print(i)

We initially set the variable to a list but later reassigned it to a datetime object and tried to iterate over it.

# Passing a datetime object to the built-in constructors causes the error

Another common cause of the error is passing a datetime object to the built-in constructors, e.g. list(), dict(), tuple() and set().

The following 4 calls to the built-in constructors cause the error.

main.py
from datetime import datetime result = datetime.today() # โ›”๏ธ TypeError: 'datetime.datetime' object is not iterable list(result) dict(result) tuple(result) set(result)

To solve the error, we have to correct the assignment and figure out where the datetime object is coming from.

Here are working examples of using the 4 built-ins.

main.py
l = list(['a', 'b', 'c']) print(l) # ๐Ÿ‘‰๏ธ ['a', 'b', 'c'] d = dict(name='Bobby Hadz', age=30) print(d) # ๐Ÿ‘‰๏ธ {'name': 'Bobby Hadz', 'age': 30} t = tuple([1, 2, 3]) print(t) # ๐Ÿ‘‰๏ธ (1, 2, 3) s = set(['a', 'b', 'a']) print(s) # ๐Ÿ‘‰๏ธ {'a', 'b'}

You have to figure out where the datetime object came from and correct the assignment.

If you need to check if an object is iterable, use a try/except statement.

main.py
my_str = 'hello' try: my_iterator = iter(my_str) for i in my_iterator: print(i) # ๐Ÿ‘‰๏ธ h, e, l, l, o except TypeError as te: print(te)

The iter() function raises a TypeError if the passed-in value doesn't support the __iter__() method or the sequence protocol (the __getitem__() method).

If we pass a non-iterable object like a datetime object to the iter() function, the except block is run.

main.py
from datetime import datetime result = datetime.today() try: my_iterator = iter(result) for i in my_iterator: print(i) except TypeError as te: print(te) # ๐Ÿ‘‰๏ธ 'datetime.datetime' object is not iterable

Examples of iterables include all sequence types (list, str, tuple) and some non-sequence types like dict, file objects and other objects that define an __iter__() or a __getitem__() method.

# Additional Resources

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

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.

Copyright ยฉ 2024 Borislav Hadzhiev