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.
1 2 3 4 5 6 7 8 9 10 11 12 |
from datetime import * # date format: (yyyy, mm, dd) dt_1 = datetime(2020, 6, 7) dt_2 = datetime(2020, 7, 8) if dt_1 > dt_2: print('dt_1 is greater than dt_2') elif dt_1 < dt_2: print('dt_1 is less than dt_2') else: print('dt_1 is equal to dt_2') |
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.
1 2 3 4 5 6 7 8 9 10 11 12 |
from datetime import * # date format: (yyyy, mm, dd, hh, mm, ss) dt_1 = datetime(2020, 6, 7, 10, 30, 25) dt_2 = datetime(2020, 6, 7, 10, 30, 20) if dt_1 > dt_2: print('dt_1 is greater than dt_2') elif dt_1 < dt_2: print('dt_1 is less than dt_2') else: print('dt_1 is equal to dt_2') |
Result:
dt_1 is greater than dt_2