In this article, we are going to learn how to Compare Two Dates in Python. We will ask user to enter date 1 and date 2 that we want to compare to know which date is earlier than the other date. We will make use of simple if and else condition in Python.
Environments & Requirements –
To run this programs we need a python interpreter.
Program to compare dates in Python
import datetime dateone = datetime.date(2022,12,18) datetwo = datetime.date(2022,12,8) print("Date1 :" , dateone) print("Date2 :" , datetwo) if dateone == datetwo: print("dateone and datetwo are equal") elif dateone > datetwo: print("dateone is greater than datetwo") else: print("dateone is smaller than datetwo")
dateone : 2022-12-18
datetwo : 2022-12-08
dateone is greater than datetwo
Program Code Explanation –
• First we have to import datetime module of Python.
• Variable dateone store the first date.
• Variable datetwo store the second date.
• if dateone is equal to datetwo then print d1 and datetwo are equal.
• And if dateone is greater than datetwo then print d1 is greater than datetwo.
• Else print dateone is smaller than datetwo.