There might be cases where you have to compare 2 dates to determine which one is earlier and which one is later. In Python, you can compare 2 date objects just like comparing 2 numbers by using comparison operators <, >, <=, >=, !=, ==. Let’s say we are given 2 date objects: date1 and date2, then we can compare them like so:
import datetime date1 = datetime.datetime(2023, 1, 1) date2 = datetime.datetime(2024, 12, 30) if(date1 < date2): print('date1 is earlier than date2') elif(date1 > date2): print('date2 is earlier than date1') else: print('date1 and date2 are the same')
The output should be:
date1 is earlier than date2
Python also allows you to subtract 2 date objects directly as if they were 2 numbers. The result will be a positive duration, a negative duration, or 0:00:00 (if the 2 dates are equal). Let’s see the example below for more clarity:
import datetime date1 = datetime.date(2023, 1, 1) date2 = datetime.date(2024, 1, 2) print(date1 - date2) print(date2 - date1) date3 = datetime.datetime(2025, 1, 3, 10, 30, 45) date4 = datetime.datetime(2025, 1, 3, 10, 30, 45) print(date3 - date4)
-366 days, 0:00:00 366 days, 0:00:00 0:00:00
If you’ve worked with other programming languages before, you’ll probably be a little surprised because the datetime handling in Python is much more simple and convenient.