Comparing dates in Python

PythonServer Side ProgrammingProgramming

Comparing dates and times is a very crucial requirement in any programming language. Python has a datetime library which has many inbuilt functions to use date and time. Interestingly date and time can also be compared like mathematical comparison between various numbers.


In the below example we have chosen to dates by passing the value of year, month and date to the date function. Then we compare the dates using a if condition and we get the appropriate result.

import datetime
# Get default date format
print("Today is: ",
date1 =, 7, 2)
date2 =, 6, 5)

# Compare dates
if (date1 > date2):
   print("Date1 > Date2")
elif (date1 < date2):
   print("Date1 < Date2")
   print("Dates are equal")

# Get Default date time format
date_time1 = datetime.datetime(2019, 7, 2,23,15,9)
date_time2 = datetime.datetime(2019, 7, 2,23,15,9)

# Compare date time
if (date_time1 == date_time2):
   print("Date Time 1 is equal to Date Time 2")
   print("Date times are unequal")


Running the above code gives us the following result −

Today is: 2019-08-01
Date1 > Date2
2019-08-01 16:34:01.061242
2019-07-02 23:15:09
Date Time 1 is equal to Date Time 2
Updated on 07-Aug-2019 08:13:45