Select Page

How to Solve Python TypeError: ‘datetime.datetime’ object is not subscriptable

by | Programming, Python, Tips

In Python, you cannot access values inside a datetime.datetime object using indexing syntax.

A datetime.datetime object represents a date (year, month and day) and time.

We can solve this error by using the dot notation to access a specific attribute. For example,

from datetime import datetime

today = datetime.today()

day = today.day

print(day)

This tutorial will go through the error in detail and how to solve it with code examples.


TypeError: ‘datetime.datetime’ object is not subscriptable

Let’s break up the error message to understand what the error means. TypeError occurs whenever you attempt to use an illegal operation for a specific data type. The part “datetime.datetime object” tells us the error concerns an illegal operation for the datetime.datetime object.

The part “is not subscriptable” tells us we cannot access an element of the generator object using the subscript operator, which is square brackets [].

A subscriptable object is a container for other objects and implements the __getitem__() method. Examples of subscriptable objects include strings, lists, tuples, and dictionaries.

We can check if an object implements the __getitem__() method by listing its attributes with the dir function. Let’s call the dir function and pass a datetime.datetime object and a str object to see their attributes.

from datetime import datetime

today = datetime.today()

print(dir(today))
['__add__', '__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__ne__', '__new__', '__radd__', '__reduce__', '__reduce_ex__', '__repr__', '__rsub__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', 'astimezone', 'combine', 'ctime', 'date', 'day', 'dst', 'fold', 'fromisocalendar', 'fromisoformat', 'fromordinal', 'fromtimestamp', 'hour', 'isocalendar', 'isoformat', 'isoweekday', 'max', 'microsecond', 'min', 'minute', 'month', 'now', 'replace', 'resolution', 'second', 'strftime', 'strptime', 'time', 'timestamp', 'timetuple', 'timetz', 'today', 'toordinal', 'tzinfo', 'tzname', 'utcfromtimestamp', 'utcnow', 'utcoffset', 'utctimetuple', 'weekday', 'year']

We can see that __getitem__ is not present in the list of attributes for the datetime.datetime object.

string = "Python"

print(dir(string))
['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isascii', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']

We can see that __getitem__ is present in the list of attributes for the str object.

If we want to check if a specific attribute belongs to an object, we can check for membership using the in operator.

from datetime import datetime

today = datetime.today()

print(type(today))

print('__getitem__' in dir(today))
<class 'datetime.datetime'>
False

The variable x is an object of the datetime.datetime class. We can see that __getitem__ is not an attribute of the datetime.datetime class.

string = "Python"
print(type(string))
print('__getitem__' in dir(string))
<class 'str'>
True

We can see that __getitem__ is an attribute of the str class.

Example

Let’s look at an example of trying to access an element of a datetime.datetime object using indexing. First, we will import the datetime class from the datetime module. Then, we will call the today() method to return the current local datetime. Once we have created the datetime.datetime object storing the current datetime, we will attempt to access the first element in the object using the subscript operator [].

from datetime import datetime

today = datetime.today()

print(today[0])

Let’s run the code to see what happens:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Input In [12], in <cell line: 5>()
      1 from datetime import datetime
      3 today = datetime.today()
----> 5 print(today[0])

TypeError: 'datetime.datetime' object is not subscriptable

The error occurs because today is a datetime.datetime object. We are trying to access values in the object as though it were a list or another subscriptable object.

Solution

We can solve this error by accessing the attributes of the datetime.datetime object using dot notation. If you are using an interactive Python shell you can use the tab key to see the autocomplete options. Otherwise you can use dir() to get the list of attributes. Let’s look at the revised code to get the day attribute of the datetime object:

from datetime import datetime

today = datetime.today()

day = today.day

print(day)

In the above code we used the dot notation to access the day attribute. Let’s run the code to see the result:

20

We successfully retrieved the day part of the current datetime.

We can also access the following relevant date and time attributes

  • week
  • month
  • year
  • minute
  • second
  • microsecond

Summary

Congratulations on reading to the end of this tutorial!

For further reading on AttributeErrors, go to the articles:

To learn more about Python for data science and machine learning, you can go to the online courses page on Python for the most comprehensive courses.

Have fun and happy researching!