

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
- Related Questions & Answers
- Comparing dates using C#
- Comparing two dates in PHP
- Comparing dates in MySQL ignoring time portion of a DateTime field?
- Comparing Timestamp in Python – Pandas
- Jasmine.js comparing arrays
- PHP Comparing Objects
- Working with Dates and Times in Python
- Python Pandas - Generate dates in a range
- Comparing enum members in Java
- Comparing enum members in C#
- Comparing Enumeration Values in Java
- Comparing two strings in MySQL?
- Comparing two strings in C++
- Comparing float value in PHP
- How do we compare Python Dates?
Advertisements