Last updated: Apr 8, 2024
Reading timeยท4 min
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])
datetime
object but datetime
objects are not subscriptable.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.
You can access an attribute using dot notation.
from datetime import datetime result = datetime.today() print(result.date()) # ๐๏ธ 2023-07-22
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 of a datetime
object.
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 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:
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.
a_list = ['bobby', 'hadz', 'com'] # ๐๏ธ <built-in method __getitem__ of list object at 0x7f71f3252640> print(a_list.__getitem__)
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.
Here is an example of how the error occurs.
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.
datetime
objectYou 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.
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.
datetime
object to the built-in constructors causes the errorAnother 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.
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.
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.
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.
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.
You can learn more about the related topics by checking out the following tutorials: