Introduction
In data analysis, it is often necessary to filter out data based on a specific date range. For example, if we want to analyze sales figures from January to March of a particular year, we need to extract only those records that fall within that time period. This is where the concept of checking if a date is between two other dates becomes useful.
In this tutorial, we will be discussing how to check if a given date is between two other dates in Python.
Checking if a date is between two dates using datetime module
One way to check if a date falls within a given range in Python is by using the datetime module.
By utilizing the datetime module, you have the ability to create various objects such as a date object (based on year, month, and day) or a datetime object (based on year, month, day, hour, and minute).
Using the datetime.date() constructor
This module provides a date object that represents a date and allows for various calculations to be done on it.
To start, you will need to import the datetime module:
import datetime
Next, create two date objects using the datetime.date() constructor. As an illustration, let's consider two date instances: one representing August 3rd, 2019 and the other representing August 9th, 2019:
start_date = datetime.date(2019, 8, 3)
end_date = datetime.date(2019, 8, 9)
Let's consider the given date:
current_date = datetime.date(2019, 8, 5)
To determine if it falls within the start and end date, we can easily utilize the Python operators ">" and "<":
start_date < current_date < end_date
This will output here
True
Another way to express the aforementioned condition is by incorporating the "and" operator:
(current_date > start_date) & (current_date < end_date)
This will output
True
Let's evaluate our code by testing it with a date that falls outside the specified range
current_date = datetime.date(2019, 7, 5)
start_date < current_date < end_date
This will output
False
Using the datetime.datetime() constructor
Now, let's explore another example that involves two datetime objects. The key difference from the previous example is that a datetime object includes both hours and minutes. By considering this additional level of detail, we can further enhance our understanding and utilization of datetime objects
import datetime
Now, let's create our two dates as datetime objects:
start_date = datetime.datetime(2019, 8, 3, 15, 30)
end_date = datetime.datetime(2019, 8, 9, 20, 42)
These two dates represent August 3rd, 2019 at 15:30 PM and August 9th, 2019 at 20:42 PM.
If we take into account the given datetime
current_date = datetime.datetime(2019, 8, 5, 0, 0)
and check whether it falls within the range of the two preceding dates
start_date < current_date < end_date
it will output
True
However
current_date = datetime.datetime(2019, 8, 3, 12, 30)
start_date < current_date < end_date
will output
False
Using Numpy to Compare Dates
Another interesting approach to determine if a date falls within a specific range is by using numpy.
Developing a function that operates element-wise
For example, numpy allows us to define two dates:
import numpy as np
start_date = np.datetime64("2019-08-03")
end_date = np.datetime64("2019-08-09")
If we take into account the given datetime
current_date = np.datetime64("2019-08-05")
and check if it is between start_date and end_date:
start_date < current_date < end_date
it will output
True
One of the benefits is the ability to define an array with multiple dates
dates = np.array(['2019-07-23', '2019-08-05', '2019-08-29'], dtype='datetime64[D]')
Furthermore, by developing a function that operates element-wise
def check_date_func(start_date,end_date, dates):
return start_date < dates < end_date
and subsequently vectorizing it:
check_date_func_vectorized = np.vectorize(check_date_func)
Now, we can utilize an array of dates
check_date_func_vectorized(start_date,end_date, dates)
Output
array([False, True, False])
Using numpy.logical_and()
Numpy provides us with a useful function called numpy.logical_and(), which allows us to perform element-wise comparison between two arrays or matrices. For example with
import numpy as np
start_date = np.datetime64("2019-08-03")
end_date = np.datetime64("2019-08-09")
dates = np.array(['2019-07-23', '2019-08-05', '2019-08-29'], dtype='datetime64[D]')
If we want to check if the dates falls between the start_date and end_date, we can do:
np.logical_and(dates > start_date, dates < end_date)
The result of the logical_and function will be a boolean value, which we can use to filter out our data accordingly. If the result is True
, then the date falls within the given range.
It will output here:
array([False, True, False])
References
Links | Site |
---|---|
datetime | docs.python.org |
operator | docs.python.org |
arrays.datetime | numpy.org |
logical_and | numpy.org |