Compare datetime in Python

You can compare two datetime objects using standard comparison operators (<, >, ==, !=). Before using the datetime class you have to import the datetime module.

Datetime with date only

In the code, there are two datetime objects. Each of them consists of year, month, and day.

The code works the same way as it would with integer values. This code will return the following result:

dt_1 is less than dt_2

Datetime with date and time

But datetime is not about date only but also time. Besides year, month, and date, you can add an hour, minute, second, and microsecond (one-millionth of a second) and tzinfo, which is the timezone.

In this example, I’m not going to add microsecond or tzinfo, but the remaining three arguments.

Result:

dt_1 is greater than dt_2