'>' not supported between instances of 'datetime.datetime' and 'str'

avatar

Borislav Hadzhiev

Last updated: Apr 20, 2022

banner

Photo from Unsplash

'>' not supported between instances of 'datetime.datetime' and 'str' #

The Python "TypeError: '>' not supported between instances of 'datetime.datetime' and 'str'" occurs when we try to compare a datetime object and a string. To solve the error, use the strptime() method to convert the string to a datetime object before the comparison.

typeerror not supported between instances of datetime datetime and str

Here is an example of how the error occurs.

main.py
from datetime import datetime today = datetime.today() print(today) # 👉️ "2022-06-01 16:32:33.536985" dt = "2026-09-01 16:32:33" # ⛔️ TypeError: '>' not supported between instances of 'datetime.datetime' and 'str' print(today > dt)

We used a comparison operator between values of incompatible types (datetime object and str) which caused the error.

To solve the error, we have to use the strptime() method to convert the string to a datetime object.

main.py
from datetime import datetime today = datetime.today() print(today) # 👉️ "2022-06-01 16:32:33.536985" # ✅ convert date string to datetime object dt = datetime.strptime( "2026-09-01 16:32:33", "%Y-%m-%d %H:%M:%S" ) print(dt) # 👉️ "2026-09-01 16:32:33" print(today > dt) # 👉️ False

The values on the left-hand and right-hand sides of the comparison operator need to be of compatible types.

The datetime.strptime() method returns a datetime object that corresponds to the provided date string, parsed according to the format.

main.py
from datetime import datetime d = '2022-11-24 09:30:00.000123' # 👇️ convert string to datetime object datetime_obj = datetime.strptime(d, '%Y-%m-%d %H:%M:%S.%f') # 👇️ Thursday, 24. November 2022 09:30AM print(datetime_obj.strftime("%A, %d. %B %Y %I:%M%p"))

The strptime() method takes the following 2 arguments:

NameDescription
date_stringThe date string that is to be converted to a datetime object
formatThe format string that should be used to parse the date string into a datetime object

For a complete list of the format codes that the strptime method supports, check out this table of the official docs.

Here is an example of converting a string that uses a different format.

main.py
from datetime import datetime today = datetime.today() print(today) # 👉️ "2022-06-01 16:32:33.536985" dt = datetime.strptime("2026/11/24 09:30", "%Y/%m/%d %H:%M") print(dt) # 👉️ 2026-11-24 09:30:00 print(today < dt) # 👉️ True

For us to be able to compare the values, they both have to be datetime objects.

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.