Compare Two Dates in Python Code Example

10-Sep-2022

.

Admin

Compare Two Dates in Python Code Example

Hi Dev,

This simple article demonstrates of Compare Two Dates in Python Code Example. if you want to see example of python compare date with current date then you are a right place. I would like to show you check date between two dates in python. you will learn 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.

so let's see following examples with output:

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...

#Python