- How to Compare two dates in Python
- Dates in Python
- How to Compare two Dates in Python?
- Example: Check if one Date is Greater than the other Date
- Example: Check if one Date is Less than the other Date
- Example: Check if Two Date are Equal
- Example: Compare Date Only
- Conclusion
- Python Compare Two Dates
- Table of contents
- How to Compare Two Dates in Python
- Example 1: Compare Two DateTime
- Example 2: Compare Two Dates
- Example 3: Compare Times of two DateTime Objects
- Compare Two Date String
- Compare Two Timestamps in Python
- About Vishal
- Related Tutorial Topics:
- Python Exercises and Quizzes
How to Compare two dates in Python
In this article, we will learn to compare two or more dates in Python. We will use some built-in modules available and some custom codes as well to see the working. Let’s first have a quick look over what are dates in Python and then how can we compare them in Python.
Dates in Python
In Python, we can work on Date functions by importing a built-in module datetime available in Python. We have date objects to work with dates. This datetime module contains dates in the form of year, month, day, hour, minute, second, and microsecond. The datetime module has many methods to return information about the date object. It requires date, month, and year values to compute the function. Date and time functions are compared like mathematical expressions between various numbers.
How to Compare two Dates in Python?
Using datetime module we can determine which date is an earlier date, which date is the latest, or which two dates are equal depending upon the dates available. We compare dates on the basis of date format as well as on the basis of time format. Now, to compare datetime objects, we can use comparison operators like greater than, less than, or equal to. We know that in Python comparison operators return boolean values (True or False). Similarly, this function will return either True or False. If the condition gets true then it will print True else False.
Example: Check if one Date is Greater than the other Date
We will use greater than operator > to check if one datetime object is greater than other datetime objects.
If we take the current date and time, and some past date and time for comparing the two dates., the current date and time will be greater than that of the past date we have chosen. Similarly, the future date and time will be greater than the current date and time.
In the given example, we have initialized three datetime objects in the format of yyyy/ mm/ dd hh : mm: ss , and then compared if the first date is greater than another date.
import datetime # date and time in yyyy/mm/dd hh:mm:ss format d1 = datetime.datetime(2020, 5, 11, 22, 50, 55) d2 = datetime.datetime(2020, 7, 11, 22, 50, 55) d3 = datetime.datetime(2020, 6, 11, 22, 50, 55) print(d1 > d2) print(d2 > d3)
We initialized three datetime objects. We take dates whose only month value differ while keeping all the values for year, day hour, minute, and second same. d1 is having a month equal to 5, d2 is having a month equal to 7 and d3 is having a month equal to 6.
As d1 is less than d2 — False and d2 is more than d3 — True.
Example: Check if one Date is Less than the other Date
In the given example, we have initialized three datetime objects in the format of yyyy/ mm/ dd hh : mm: ss , and then compared if the first date is less than another date.
import datetime # date and time in yyyy/mm/dd hh:mm:ss format d1 = datetime.datetime(2020, 5, 11, 22, 50, 55) d2 = datetime.datetime(2020, 7, 11, 22, 50, 55) d3 = datetime.datetime(2020, 6, 11, 22, 50, 55) print(d1 < d2) print(d2 < d3)
We initialized three datetime objects. We take dates whose only month value differ while keeping all the values for year, day hour, minute, and second same. d1 is having month equal to 5, d2 is having month equal to 7 and d3 is having month equal to 6.
As d1 is less than d2 - False and d2 is more than d3 - True.
Example: Check if Two Date are Equal
We will use equal to comparison operator = to check if one datetime object has the same value as the other.
In the following program, we initialize three datetime objects and then check if both datetime objects have the same date or not.
import datetime # date and time in yyyy/mm/dd hh:mm:ss format d1 = datetime.datetime(2020, 5, 11, 22, 50, 55) d2 = datetime.datetime(2020, 5, 11, 22, 50, 55) d3 = datetime.datetime(2020, 6, 11, 22, 50, 55) print(d1 == d2) print(d2 == d3)
We initialized three datetime objects. We take dates whose only month value differ while keeping all the values for year, day hour, minute, and second same. d1 is having month equal to 5, d2 is having month equal to 5 and d3 is having month equal to 6.
As d1 is equal to d2 - True and d2 is not equal to d3 - False
Example: Compare Date Only
In the following program, we initialize three datetime objects, and compare only the dates, and ignore the time part. The datetime object contains date and time both. So, if we want to fetch date only then use date() method as we did in the below example.
import datetime # date and time in yyyy/mm/dd hh:mm:ss format d1 = datetime.datetime(2020, 5, 11, 22, 50, 55) d2 = datetime.datetime(2020, 5, 11, 7, 50, 55) d3 = datetime.datetime(2020, 6, 11, 22, 50, 55) print(d1.date() == d2.date()) print(d1.date() == d3.date()) print(d1.date() < d2.date()) print(d1.date() < d3.date()) print(d1.date() >d2.date()) print(d1.date() > d3.date())
True
False
False
True
False
False
Conclusion
In this article, we learned to compare two dates either by using datetime module or timedelta module. We used some custom codes as well. For example, we used three dates in the given format and compare the past dates with present dates on the basis of month and time.
Python Compare Two Dates
In this lesson, you’ll learn how to compare two dates or datetime in Python.
You’ll learn how to:
- Check if a given date is greater or less than another date.
- Compare two timestamps
- Compare two date string
Table of contents
How to Compare Two Dates in Python
Use comparison operators (like , =, !=, etc.) to compare dates in Python. Let’s see the steps to compare dates with the help of the datetime module.
- import datetime modulePython datetime module provides various functions to create and manipulate the date and time. Use the from datetime import datetime statement to import a datetime class from a datetime module.
- Convert date string to a datetime object If dates are in a string format, we need to convert both date strings to a datetime object before comparing them.
Use the strptime(date_str, format) function to convert a date string into a datetime object as per the corresponding format . For example, the %Y/%m/%d format codes are for yyyy-mm-dd . - Compare two datetime objects Use comparison operators (like < , >, = , != , etc.) to compare dates in Python. For example, datetime_1 > datetime_2 to check if a datetime_1 is greater than datetime_2.
- Compare two dates If you want to compare only the dates of the DateTime object, use the date() method to extract only the date part from the datetime object.
- Compare two time To compare only the time of the DateTime object, use the time() method to extract only the time part from the datetime object.
Example 1: Compare Two DateTime
In this example, we’ll check:
- If the datetime_1 is greater than another datetime.
- If the datetime_1 is lower than datetime_2.
from datetime import datetime def compare_dates(date1, date2): print('Date1:', date1) print('Date2:', date2) if date1 > date2: print('Date1 is greater than date2') else: print('Date1 is lower than date2') dt1 = datetime(2022, 9, 13) # today's datetime today = datetime.now() compare_dates(dt1, today) dt1 = datetime(2022, 9, 13) dt2 = datetime(2021, 11, 23) compare_dates(dt1, dt2)
Date1: 2022-09-13 00:00:00 Date2: 2022-10-07 15:12:52.970943 Date1 is lower than date2 Date1: 2022-09-13 00:00:00 Date2: 2021-11-23 00:00:00 Date1 is greater than date2
Example 2: Compare Two Dates
Let’s assume you have two datetime objects. One only has the date, and the other one has the date & time parts, and you want to compare the dates only (and not the time).
Now, If you want to compare only the dates of DateTime objects, just use the date() method to extract only the date part from the datetime object.
from datetime import datetime # input dates d1 = datetime(2022, 6, 27).date() d2 = datetime(2022, 6, 27).date() d3 = datetime(2021, 5, 14).date() d4 = datetime(2022, 10, 10).date() # omit .date() function if you want to compare the entire datetime object # use .date() id you want to compare only the date part of it # date equality check print('Date_1:', d1, 'Date_2:', d2, 'Date3:', d3) print('Date_1 and Date_2 are equal:', d1 == d2) print('Date_1 and Date_3 are equal:', d1 == d3) # check if date is greater than another date print('Date_1:', d1, 'Date_3:', d3, 'Date_4:', d4) print('date_1 is greater than date_3:', d1 > d3) print('date_1 is greater than date_4:', d1 > d4) # check if date is less than another date print('Date_1:', d1, 'Date_3:', d3, 'Date_4:', d4) print('date_1 is less than date_3:', d1 < d3) print('date_1 is less than date_4:', d1 < d4) # date not equal to check print('Date_1:', d1, 'Date_2:', d2, 'Date__3:', d3) print('Date_1 and Date_2 are NOT equal:', d1 != d2) print('Date_1 and Date_3 are NOT equal:', d1 != d3)
Date_1: 2022-06-27 Date_2: 2022-06-27 Date3: 2021-05-14 Date_1 and Date_2 are equal: True Date_1 and Date_3 are equal: False Date_1: 2022-06-27 Date_3: 2021-05-14 Date_4: 2022-10-10 date_1 is greater than date_3: True date_1 is greater than date_4: False Date_1: 2022-06-27 Date_3: 2021-05-14 Date_4: 2022-10-10 date_1 is less than date_3: False date_1 is less than date_4: True Date_1: 2022-06-27 Date_2: 2022-06-27 Date__3: 2021-05-14 Date_1 and Date_2 are NOT equal: False Date_1 and Date_3 are NOT equal: True
Example 3: Compare Times of two DateTime Objects
Let’s assume you have two datetime objects. One only has the time, and the other one has the date & time parts, and you want to compare the times only (and not the date).
Use the time() method to extract only the time part from the datetime object.
from datetime import datetime # date in yyyy/-mm-dd hh:mm:ss format dt_1 = datetime(2022, 6, 27, 18, 45, 53) dt_2 = datetime(2022, 6, 27, 21, 12, 34) # use .time() if you want to compare only the time part of it # date equality check print('Time_1:', dt_1.time(), 'Time_2:', dt_2.time()) print('Both times are equal:', dt_1.time() == dt_2.time()) print('Times not equal:', dt_1.time() != dt_2.time()) print('Time_1 is greater than Time_2:', dt_1.time() > dt_2.time()) print('Time_1 is less than Time_2:', dt_1.time() < dt_2.time())
Time_1: 18:45:53 Time_2: 21:12:34 Both times are equal: False Times not equal: True Time_1 is greater than Time_2: False Time_1 is less than Time_2: True
Compare Two Date String
There may be a case in which dates are in a string format. Before comparing them, we need to convert both date strings to a datetime object.
Use the strptime(date_str, format) function to convert a date string into a datetime object as per the corresponding format . The format codes are standard directives for mentioning the string format for parsing. For example, the %Y/%m/%d format codes are for yyyy-mm-dd .
from datetime import datetime def compare_dates(date1, date2): # convert string to date dt_obj1 = datetime.strptime(date1, "%Y-%m-%d %H:%M:%S") dt_obj2 = datetime.strptime(date2, "%Y-%m-%d %H:%M:%S") print('Date1:', dt_obj1) print('Date2:', dt_obj2) if dt_obj1 == dt_obj2: print('Both dates are equal') elif dt_obj1 > dt_obj2: print('Date1 is greater than date2') else: print('Date1 is lower than date2') # datetime in yyyy-mm-dd hh:mm:ss format dt_str1 = '2022-10-29 8:32:49' dt_str2 = '2022-5-7 4:14:58' compare_dates(dt1_str1, dt2_str2)
Date1: 2022-10-29 08:32:49 Date2: 2022-05-07 04:14:58 Date1 is greater than date2
Compare Two Timestamps in Python
A timestamp is encoded information generally used in UNIX, which indicates the date and time at which a particular event has occurred. This information could be accurate to the microseconds. It is a POSIX timestamp corresponding to the datetime instance.
To compare Python timestamp objects, we can use the same conditional operator we used to compare dates.
from datetime import datetime # input timestamp ts1 = datetime(2022, 6, 27, 18, 45, 32).timestamp() # get current timestamp ts2 = datetime.now().timestamp() print('Timestamp_1:', ts1, 'Timestamp_2:', ts2) # timestamp equality check print('Timestamp_1 and Timestamp_2 are equal:', ts1 == ts2) # check if timestamp_1 is greater than another timestamp print('Timestamp_2 is greater than Timestamp_1:', ts2 > ts1) # check if timestamp_1 is less than another timestamp print('Timestamp_1 is less than Timestamp_2:', ts1 < ts2) # timestamp not equal to check print('Timestamp_1 is NOT equal to Timestamp_2:', ts1 != ts2)
Timestamp_1: 1656335732.0 Timestamp_2: 1665393979.484924 Timestamp_1 and Timestamp_2 are equal: False Timestamp_2 is greater than Timestamp_1: True Timestamp_1 is less than Timestamp_2: True Timestamp_1 is NOT equal to Timestamp_2: True
Did you find this page helpful? Let others know about it. Sharing helps me continue to create free Python resources.
About Vishal
I’m Vishal Hule, Founder of PYnative.com. I am a Python developer, and I love to write articles to help students, developers, and learners. Follow me on Twitter
Related Tutorial Topics:
Python Exercises and Quizzes
Free coding exercises and quizzes cover Python basics, data structure, data analytics, and more.
- 15+ Topic-specific Exercises and Quizzes
- Each Exercise contains 10 questions
- Each Quiz contains 12-15 MCQ