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 module
Python datetime module provides various functions to create and manipulate the date and time. Use the
from datetime import datetime
statement to import adatetime
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 thestrptime(date_str, format)
function to convert a date string into a datetime object as per the correspondingformat
. For example, the%Y/%m/%d
format codes are foryyyy-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)
Output:
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)
Output:
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.
Example:
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())
Output:
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
.
Example:
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)
Output:
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.
Example:
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)
Output:
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
Leave a Reply