How to Compare Datetime of Two Strings in Python?

Estimated read time 2 min read

To compare the datetime values of two strings in Python, you need to convert the strings to datetime objects and then perform the comparison. The datetime module in Python provides various methods for parsing and comparing datetime values. Here’s an example:

from datetime import datetime

date_string1 = "2023-05-28 09:30:00"
date_string2 = "2023-05-28 10:00:00"

# Convert strings to datetime objects
datetime1 = datetime.strptime(date_string1, "%Y-%m-%d %H:%M:%S")
datetime2 = datetime.strptime(date_string2, "%Y-%m-%d %H:%M:%S")

# Compare datetime values
if datetime1 < datetime2:
    print("datetime1 is earlier than datetime2")
elif datetime1 > datetime2:
    print("datetime1 is later than datetime2")
else:
    print("datetime1 and datetime2 are equal")

In this example, date_string1 and date_string2 represent the datetime values in string format. The strptime() method from the datetime module is used to parse the strings and convert them into datetime objects, using the corresponding format string ("%Y-%m-%d %H:%M:%S").

After converting the strings to datetime objects (datetime1 and datetime2), you can compare them using comparison operators (<, >, ==, etc.). The comparison result will indicate whether one datetime is earlier, later, or equal to the other.

Make sure the format string used in strptime() matches the format of your datetime strings. Adjust the format string as per your specific datetime string format.

By converting the strings to datetime objects and performing the comparison, you can effectively compare the datetime values of two strings in Python.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply