How to Compare Timestamps in Python?

Estimated read time 1 min read

To compare timestamps in Python, you can use the comparison operators (<, <=, >, >=, ==, !=) to compare datetime objects or timestamp objects. Here’s an example:

import datetime

timestamp1 = datetime.datetime(2023, 5, 30, 10, 30, 0)
timestamp2 = datetime.datetime(2023, 5, 30, 11, 0, 0)

result = timestamp1 < timestamp2
print(result)

Output:

True

In this example, we create two datetime objects: timestamp1 and timestamp2. We then compare them using the < operator to check if timestamp1 is less than timestamp2. Since timestamp1 represents an earlier time, the result is True.

You can use any of the comparison operators (<, <=, >, >=, ==, !=) to compare timestamps in a similar manner. The comparison is performed based on the chronological order of the timestamps.

Make sure to import the datetime module before using it. The datetime module provides various functions and classes for working with dates and times in Python.

If you’re working with timestamps in a different format or from an external source, you might need to parse them into datetime objects using appropriate functions such as strptime() from the datetime module.

By using the comparison operators, you can compare timestamps in Python and obtain the comparison result based on their chronological order.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply