Sling Academy
Home/Python/How to Compare 2 Dates in Python

How to Compare 2 Dates in Python

Last updated: January 16, 2023

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)

Output:

-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.

Next Article: How to Format Date and Time in Python

Series: Date and Time in Python

Python

You May Also Like

  • Python TypeError: write() argument must be str, not bytes
  • 4 ways to install Python modules on Windows without admin rights
  • Python TypeError: object of type ‘NoneType’ has no len()
  • Python: How to access command-line arguments (3 approaches)
  • Understanding ‘Never’ type in Python 3.11+ (5 examples)
  • Python: 3 Ways to Retrieve City/Country from IP Address
  • Using Type Aliases in Python: A Practical Guide (with Examples)
  • Python: Defining distinct types using NewType class
  • Using Optional Type in Python (explained with examples)
  • Python: How to Override Methods in Classes
  • Python: Define Generic Types for Lists of Nested Dictionaries
  • Python: Defining type for a list that can contain both numbers and strings
  • Using TypeGuard in Python (Python 3.10+)
  • Python: Using ‘NoReturn’ type with functions
  • Type Casting in Python: The Ultimate Guide (with Examples)
  • Python: Using type hints with class methods and properties
  • Python: Typing a function with default parameters
  • Python: Typing a function that can return multiple types
  • Python: Typing a function with *args and **kwargs