Table of Contents
Python allows us to store and work with date values very efficiently by providing the datetime
module. This module has datetime
objects that can store date and time values. There are other third-party packages as well that allows us to work with such values. We can also store dates as strings in Python.
In this tutorial, we will check if date is between two dates in Python.
Check if Date Is Between Two Dates in Python
There are multiple ways to check if date is between two dates in Python. Let’s go through them.
Using the datetime.Datetime
Object to Check if Date Is Between Two Dates in Python
As discussed earlier, we can store date values in datetime
objects. We can compare such objects using relational operators.
We can use them to check if date is between dates in Python. We can use them to compare whether a given date is less than and greater than the given ranges to see if it returns True or False.
See the code below.
1 2 3 4 5 6 7 8 |
import datetime d1 = datetime.datetime(2022, 1,1) d2 = datetime.datetime(2022,2,2) d3 = datetime.datetime(2022,3,3) print(d1<d2<d3) print(d2<d1<d3) |
Output:
False
In the above example, we define three dates of d1
, d2
, and d3
. We perform two comparisons. In the first one, we check whether d2
date lies between d1
and d3
and the comparison returns True. We then check whether d1
lies between d2
and d3
and we observe that False is returned since the condition is not True.
Further reading:
Using Tuples to Check if Date Is Between Two Dates in Python
This method does not involve the use of datetime
objects and also we will not consider the year in a date. In this technique, we will use tuples to store the day and month of a date.
To check if date is between two dates in Python, we will similarly use relational operators as we did previously to compare different tuples that store the dates.
See the code below.
1 2 3 4 5 6 7 |
d1 = (1,31) d2 = (2,22) d3 = (3,13) print(d1<d2<d3) print(d2<d1<d3) |
Output:
False
Here, first element is tuple is month and second element is day.
In the above example, we create three dates with only their respective days and months in three tuples. The three tuples are compared to check if one tuple is between the other two tuples. The output is True where the date is between two dates and False when the date is not between the given dates.
Conclusion
This article demonstrated different ways to check if date is between two dates in Python.
We first discussed date values in Python and how they are stored in datetime
objects. In the first method, we used such objects and compared them using relational operators to check if date is between two dates in Python.
In the second method, we similarly used tuples to check if date is between two dates in Python. The limitation of this method is that we are discarding the year of the date and only use the day and month value.