How to Resolve Python Error "TypeError: '>' not supported between instances of 'datetime.datetime' and 'str'" (and other comparisons)
When working with dates and times in Python, comparing datetime
objects is a common task (e.g., checking if one date is before or after another). However, attempting to directly compare a datetime.datetime
object with a plain string using operators like >
, <
, >=
, or <=
will result in a TypeError: '>' not supported between instances of 'datetime.datetime' and 'str'
(or similar, depending on the operator).
This guide explains why this type mismatch occurs during comparison and provides the standard solution using datetime.strptime()
to ensure you are comparing compatible types.
Understanding the Error: Type Compatibility in Comparisons
Python's comparison operators (>
, <
, >=
, <=
, ==
, !=
) are defined to work between objects of compatible types. You can compare two numbers, two strings (lexicographically), or two datetime
objects (chronologically). However, Python doesn't inherently know how to order a datetime
object relative to an arbitrary string. Does "2024-10-27"
come before or after the datetime
object representing noon on that day? Python raises a TypeError
because the comparison is undefined between these distinct types.
The Cause: Comparing datetime
Objects and Strings
The error occurs when you use a comparison operator with a datetime.datetime
object on one side and a str
object on the other.
# Error Scenario
from datetime import datetime
now_datetime = datetime.now() # A datetime object
date_string = "2025-01-01 12:00:00" # A string representation
print(f"Datetime object: {now_datetime} (Type: {type(now_datetime)})")
print(f"Date string: '{date_string}' (Type: {type(date_string)})")
try:
# ⛔️ TypeError: '>' not supported between instances of 'datetime.datetime' and 'str'
# Trying to compare a datetime object directly with a string.
is_future = date_string > now_datetime
print(f"Is future? {is_future}")
except TypeError as e:
print(e)
Output:
Datetime object: 2025-04-27 17:41:24.828735 (Type: <class 'datetime.datetime'>)
Date string: '2025-01-01 12:00:00' (Type: <class 'str'>)
'>' not supported between instances of 'str' and 'datetime.datetime'
Solution: Convert the String to a datetime
Object using strptime()
The correct approach is to ensure both operands are datetime
objects before comparison. Use the datetime.strptime()
class method to parse the date string into a corresponding datetime
object.
The strptime()
Method
datetime.strptime(date_string, format_code)
parses a string representing a date and time according to a specified format code.
date_string
: The input string containing the date/time information.format_code
: A string composed of special directives (like%Y
,%m
,%d
,%H
,%M
,%S
) that must exactly match the structure of thedate_string
.
Example and Fix
from datetime import datetime
now_datetime = datetime.now()
date_string = "2025-01-01 12:00:00"
# Format code MUST match the date_string structure
format_code = "%Y-%m-%d %H:%M:%S"
print(f"Original string: '{date_string}'")
try:
# ✅ Convert the string to a datetime object using the correct format
future_datetime = datetime.strptime(date_string, format_code)
print(f"Converted datetime: {future_datetime} (Type: {type(future_datetime)})")
# ✅ Now compare two datetime objects
is_after = future_datetime > now_datetime
print(f"\nIs '{date_string}' after now? {is_after}") # Output will depend on current time
is_before = future_datetime < now_datetime
print(f"Is '{date_string}' before now? {is_before}")
except ValueError as e:
print(f"ValueError during strptime: Check if string '{date_string}' matches format '{format_code}'. Error: {e}")
except TypeError as e:
print(f"TypeError during comparison (should not happen now): {e}")
Output:
Original string: '2025-01-01 12:00:00'
Converted datetime: 2025-01-01 12:00:00 (Type: <class 'datetime.datetime'>)
Is '2025-01-01 12:00:00' after now? False
Is '2025-01-01 12:00:00' before now? True
By converting the string to a datetime
object, the comparison becomes a valid chronological check between two points in time.
Matching the Format Code
It is essential that the format_code
string precisely mirrors the format of your date_string
.
- If
date_string
is"01/Nov/2024 15:30"
,format_code
must be"%d/%b/%Y %H:%M"
. - If
date_string
is"20241027"
,format_code
must be"%Y%m%d"
.
Refer to the Python strftime()
and strptime()
format codes documentation for a complete list of directives. Mismatched formats will raise a ValueError
.
from datetime import datetime
date_string_alt = "27-Oct-2024_10:00:05"
format_code_alt = "%d-%b-%Y_%H:%M:%S" # Matches the string
dt_object_alt = datetime.strptime(date_string_alt, format_code_alt)
print(f"Parsed alternative format: {dt_object_alt}")
Output:
Parsed alternative format: 2024-10-27 10:00:05
Alternative (Incorrect for Chronological Comparison): Converting Datetime to String
You could convert the datetime
object to a string using strftime()
and then compare two strings. However, this is generally wrong for date/time comparisons. String comparison is lexicographical (alphabetical/character-by-character), not chronological.
from datetime import datetime
dt1 = datetime(2024, 1, 10) # Jan 10th
dt2 = datetime(2024, 5, 9) # May 9th
str1 = dt1.strftime("%Y-%m-%d") # "2024-01-10"
str2 = dt2.strftime("%Y-%m-%d") # "2024-05-09"
# Lexicographical comparison (works correctly for YYYY-MM-DD format)
print(f"String comparison ('{str1}' < '{str2}'): {str1 < str2}") # Output: True
# --- Example where string comparison fails chronologically ---
str1_bad = dt1.strftime("%d-%m-%Y") # "10-01-2024"
str2_bad = dt2.strftime("%d-%m-%Y") # "09-05-2024"
# Chronologically, dt1 is before dt2
print(f"Datetime comparison (dt1 < dt2): {dt1 < dt2}") # Output: True
# Lexicographically, "10..." comes AFTER "09..."
print(f"Bad String comparison ('{str1_bad}' < '{str2_bad}'): {str1_bad < str2_bad}") # Output: False (Incorrect result!)
Output:
String comparison ('2024-01-10' < '2024-05-09'): True
Datetime comparison (dt1 < dt2): True
Bad String comparison ('10-01-2024' < '09-05-2024'): False
Unless you use a string format where lexicographical order perfectly matches chronological order (like YYYY-MM-DD HH:MM:SS
), comparing strings will give incorrect results for date/time logic. Always convert strings to datetime
objects for comparisons.
Debugging the Error (type()
)
When you encounter this TypeError
:
- Examine the comparison line (
>
,<
,>=
,<=
). - Identify the variables/values on the left and right sides.
- Print their types:
print(type(left_operand))
,print(type(right_operand))
. - You will see one is
<class 'datetime.datetime'>
and the other is<class 'str'>
, confirming the mismatch. - Apply Solution 3: Convert the string operand to a
datetime
object usingstrptime()
with the correct format code.
Conclusion
The TypeError: '>' not supported between instances of 'datetime.datetime' and 'str'
(and similar for other operators) occurs because Python can not perform chronological comparisons between a datetime
object and a string.
The definitive solution is to ensure both operands are datetime
objects before the comparison. Use the datetime.strptime(date_string, format_code)
method to convert the string representation into a proper datetime
object, making sure the format_code
precisely matches the structure of the date_string
. Avoid comparing string representations of dates unless you are certain the format guarantees correct lexicographical ordering that matches chronological order (like ISO 8601 format).