How to Compare Two Dates in Python?

By Hardik Savani October 30, 2023 Category : Python

Now, let's see tutorial of python check if date is greater than. this example will help you python check if date is greater than today. if you want to see example of compare two dates in python then you are a right place. I explained simply step by step check date between two dates in python. Let's see bellow example compare two dates in python.

In this example, I will give two examples one example will compare with today's date, and second example compare with two custom dates. so let's see both examples and use them for you.

You can use these examples with python3 (Python 3) version.

Example 1: Python Check if Date is Greater than Today

main.py

from datetime import datetime
  
myDateString = "2022-06-28"
myDate = datetime.strptime(myDateString, "%Y-%m-%d")
  
# Today's Date is 2022-06-27
todayDate = datetime.now()
  
if myDate.date() > todayDate.date():
    print("Date is Greater than Today")
else:
    print("Date is not Greater than Today")

Output:

Date is Greater than Today

Example 2: Python Compare with Two Dates

main.py

from datetime import datetime
  
oneDate = "2022-06-26"
oneDateObj = datetime.strptime(oneDate, "%Y-%m-%d")
  
secondDate = "2022-06-25"
secondDateObj = datetime.strptime(secondDate, "%Y-%m-%d")
  
if oneDateObj.date() > secondDateObj.date():
    print("First Date is Greater...")
else:
    print("Second Date is Greater...")

Output:

 
First Date is Greater...

I hope it can help you...

Tags :
Shares