Python - How to compare dates

By xngo on June 12, 2019

Dates in Python can be easily compared using the comparison operators: <, >, <=, >=, !=, ==. Here are some examples.

#!/usr/bin/python3
 
# Import datetime module.
import datetime 
 
# Date in yyyy/mm/dd format.
d1_1990 = datetime.datetime(1990, 5, 23) 
d2_2018 = datetime.datetime(2018, 6, 14) 
d3_2018 = datetime.datetime(2018, 6, 14)
 
# Compare the dates will return either True or False.
print("d1_1990 is greater than d2_2018 : ", d1_1990 >  d2_2018) 
print("d1_1990 is less    than d2_2018 : ", d1_1990 <  d2_2018) 
print("d2_2018 is equal to     d3_2018 : ", d2_2018 == d3_2018) 
print("d1_1990 is not equal to d2_2018 : ", d1_1990 != d2_2018) 

Output

d1_1990 is greater than d2_2018 :  False
d1_1990 is less    than d2_2018 :  True
d1_1990 is not equal to d2_2018 :  True
d2_2018 is equal to     d3_2018 :  True

About the author

Xuan Ngo is the founder of OpenWritings.net. He currently lives in Montreal, Canada. He loves to write about programming and open source subjects.