In this tutorial, you will learn how to check if a date is between two specific dates in Python. Date manipulations are always an important aspect of any data-related tasks, be it data analysis or data science.
Python provides easy-to-use libraries and methods to handle such tasks, hence making it easier for the coder to perform date-related operations. Let’s delve into it and see how we can solve this problem.
Step 1: Import the Required Libraries
Before we can compare dates, we will need to import the datetime module. This module contains several functions for manipulating dates and times.
1 |
import datetime |
Step 2: Define the Dates
Next, let’s define our dates. We need three dates – the start date, the end date, and the date we want to compare to see if it lies between the start and end dates.
1 2 3 |
start_date = datetime.date(2020, 5, 1) end_date = datetime.date(2020, 5, 30) check_date = datetime.date(2020, 5, 15) |
Step 3: Check if Check_Date is Between Start_Date and End_Date
We will now check if the check_date lies between the start_date and the end_date. The if statement is used for this purpose.
1 2 3 4 |
if start_date <= check_date <= end_date: print("Date is in range") else: print("Date is not in range") |
The above code will print “Date is in the range” if the check_date is between the start_date and end_date; otherwise, it will print “Date is not in the range“.
Full Code
Here is the complete code for checking if a date is between two dates in Python:
1 2 3 4 5 6 7 8 9 10 |
import datetime start_date = datetime.date(2020, 5, 1) end_date = datetime.date(2020, 5, 30) check_date = datetime.date(2020, 5, 15) if start_date <= check_date <= end_date: print("Date is in range") else: print("Date is not in range") |
Output:
Date is in range
Conclusion
In this tutorial, we learned how to check if a date is between two dates in Python. Understanding how to carry out date manipulations is an essential skill especially when working with time-series data. Python’s datetime makes it rather easy to perform these operations.
The key part to understand is how the comparison of dates happens in Python. Other than that, the concept is quite simple and straightforward.
Keep practicing to get a strong hold on Python datetime manipulations. You never know when this will come in handy in your data analysis operations. Happy coding!