Last updated: Apr 8, 2024
Reading timeยท2 min
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) # ๐๏ธ "2023-07-20 15:10:36.783382" 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.
strptime
method to convert the string to a datetime objectTo 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) # ๐๏ธ "2023-07-20 15:12:00.883541" # โ Convert a date string to a 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 a 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) # ๐๏ธ "2023-07-20 15:13:29.918900" 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.
For a complete list of the format codes that the strptime
method supports,
check out
this table
of the official docs.