Python - How To Compare Two Dates in Python

ID : 393

viewed : 105

Tags : PythonPython DateTime

vote vote

92

The tutorial explains how to compare two dates in Python. It has multiple methods to identify which date is greater, so the tutorial also lists different example codes to elaborate on different approaches.

Use the datetime Module and the </> Operator to Compare Two Dates in Python

datetime and simple comparison operators < or > can be used to compare two dates. The module provides the timedelta method to manipulate dates and times. The timedelta() method takes the number of days as the input and can perform arithmetics on it.

An example code is given below:

from datetime import datetime, timedelta  previous_date = datetime.now() - timedelta(days=1) current_date = datetime.now() print(present > past) 

Output:

True 

Use datetime.date() Method to Compare Two Dates in Python

datetime.date() can also be used to compare two dates. The datetime.date() method takes year, month, day as its input. Create two dates to be compared and use a simple comparison operator to compare two dates.

An example code is given below.

import datetime  first_date = datetime.date(2020, 12, 16) second_date = datetime.date(2015, 12, 16)  result = first_date < second_date print(result) 

Output:

False 

Use the time Module to Compare Two Dates in Python

The time module provides the strptime method to manipulate the dates. It takes the date in string format as the input and converts it into Python’s date format. Later, a simple comparison can be performed to compare two dates.

An example code is givens as below.

import time  first_date = "30/11/2020" second_date = "12/10/2019"  formatted_date1 = time.strptime(first_date, "%d/%m/%Y") formatted_date2 = time.strptime(second_date, "%d/%m/%Y") print(formatted_date1 > formatted_date2) 

Output:

True 

Use the datetime Module to Compare Two Dates

The datetime module provides the datetime() method that takes three parameters to create a date from the year, month, and day. After getting dates, they can be compared using the comparison operators.

An example code is given below:

import datetime  # date in yy/mm/dd format first_date = datetime.datetime(2020, 5, 11) second_date = datetime.datetime(2020, 6, 10)  print("first date is greater than second_date: ", first_date > second_date) print("first date is smaller than second_date: ", first_date < second_date) print("first date is not equal to second_date: ", first_date != second_date) 

Output:

first date is greater than second_date:  False first date is smaller than second_date:  True first date is not equal to second_date:  True 

  • Related HOW TO?