Borislav Hadzhiev
Last updated: Apr 20, 2022
Photo from Unsplash
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.
Here is an example of how the error occurs.
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.
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.
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:
Name | Description |
---|---|
date_string | The date string that is to be converted to a datetime object |
format | The 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.
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.