Computer >> Computer tutorials >  >> Programming >> Python

Comparing dates in Python


Comparing dates and times is a very crucial requirement in any programming language. Python has a datetime library which has many inbuilt functions to use date and time. Interestingly date and time can also be compared like mathematical comparison between various numbers.

Example

In the below example we have chosen to dates by passing the value of year, month and date to the date function. Then we compare the dates using a if condition and we get the appropriate result.

import datetime
# Get default date format
print("Today is: ",datetime.date.today())
date1 = datetime.date(2019, 7, 2)
date2 = datetime.date(2019, 6, 5)

# Compare dates
if (date1 > date2):
   print("Date1 > Date2")
elif (date1 < date2):
   print("Date1 < Date2")
else:
   print("Dates are equal")

# Get Default date time format
print(datetime.datetime.now())
date_time1 = datetime.datetime(2019, 7, 2,23,15,9)
date_time2 = datetime.datetime(2019, 7, 2,23,15,9)

# Compare date time
print(date_time2)
if (date_time1 == date_time2):
   print("Date Time 1 is equal to Date Time 2")
else:
   print("Date times are unequal")

Output

Running the above code gives us the following result −

Today is: 2019-08-01
Date1 > Date2
2019-08-01 16:34:01.061242
2019-07-02 23:15:09
Date Time 1 is equal to Date Time 2