VOOZH about

URL: https://www.geeksforgeeks.org/python/comparing-dates-python/

⇱ Comparing dates in Python - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Comparing dates in Python

Last Updated : 11 Jul, 2025

In Python, comparing dates is straightforward with the help of the datetime module. You can use basic comparison operators like <, >, ==, and != to compare two date or datetime objects directly. Below are a few common and practical ways to compare and sort dates in Python.

Basic Date Comparison

You can directly compare two datetime objects using standard comparison operators.


Output
d1 > d2: False
d1 < d2: True
d1 != d2: True

Explanation:

  • datetime() creates a date-time object.
  • operators like >, <, and != work directly on datetime objects.

Sorting a List of Dates

Dates can be stored in a list and sorted using the sort() method.


Output
2011-04-07
2011-05-02
2015-06-29
2025-04-22

Explanation:

  • date.today() returns the current date.
  • timedelta(days=25) adds days to a date.
  • sort() arranges the list of dates in ascending order.

Using timedelta for Comparison

We can also use subtraction between date objects and compare the result using timedelta.


Output
d1 > d2: False
d1 < d2: True
d1 != d2: True

Explanation:

  • Subtracting two dates returns a timedelta object.
  • Comparing with timedelta(0) shows which date is earlier/later.
  • != checks if the dates are different.

Also read: sort(), timedelta, datetime object.

Comment
Article Tags: