Python Comparing Dates

It is possible to compare two 'date' class objects just like comparing two numbers.For example, d1 and d2 are to be compared, we can write:

d1 == d2

d1> d2

d1

These expressions return either True or False. Similarly it is possible to compare the 'datetime' class objects also.

Comparing Dates

In Program, we are accepting date of births of two persons and determining who is older. This is done by first storing the date of births in two separate date class objects b1 and b2 and then comparing them using the if statement.

Compare Two Dates Example:

CopiedCopy Code

#to know who is older 
from datetime import * 
#enter birth dates and store into date class objects 
d1, m1, y1 = [int(x) for x in input("First date (DD/MM/YYYY): ").split('/')] 
b1 = date(y1, m1, d1) 
d2, m2, y2 = [int(x) for x in input("Second date (DD/MM/YYYY): ").split('/')] 
b2 = date(y2, m2, d2) 
#compare the birth dates 
if b1 == b2: 
   print('Both entered are of equal') 
elif b1 > b2: 
   print('The second entered is elder') 
else: 
   print('The first entered is elder')