This tutorial will discuss about a unique way to check if date is between two dates in Python.
Suppose we have three dates in the string format like this,
dateStr = '2023-04-26' startDateStr = '2023-04-01' endDateStr = '2024-04-30'
Now we want to check if the date dateStr is between the startDateStr and endDateStr or not. We have created a method for this,
from datetime import datetime def is_between(dateStr, startDateStr, endDateStr): # Checks if a given date is between two other dates (inclusive). # Returns True if the date is between the start and end dates, # False otherwise. # Convert dates in string format to datetime objects date_obj = datetime.strptime(dateStr, '%Y-%m-%d').date() startDate = datetime.strptime(startDateStr, '%Y-%m-%d').date() endDate = datetime.strptime(endDateStr, '%Y-%m-%d').date() # check if dateObj is between startDate and endDate if startDate <= date_obj <= endDate: return True else: return False
It accepts three dates in string format and checks if the first state exists between the second and 3rd date or not. Basically, it checks if the given date dateStr is between startDateStr & endDateStr and returns true if the date is between these two dates.
Inside the method we will convert the date strings into the actual date objects from the datetime module. Then we will check if the first date object i.e. date_obj is between the startDate and endDate using the <= operators.
Frequently Asked:
In the below example we are going to use this method to check if a date ‘2023-04-26’ exists between the ‘2023-04-01’ and ‘2024-04-30’.
Let’s see the complete example,
from datetime import datetime def is_between(dateStr, startDateStr, endDateStr): # Checks if a given date is between two other dates (inclusive). # Returns True if the date is between the start and end dates, # False otherwise. # Convert dates in string format to datetime objects date_obj = datetime.strptime(dateStr, '%Y-%m-%d').date() startDate = datetime.strptime(startDateStr, '%Y-%m-%d').date() endDate = datetime.strptime(endDateStr, '%Y-%m-%d').date() # check if dateObj is between startDate and endDate if startDate <= date_obj <= endDate: return True else: return False dateStr = '2023-04-26' startDateStr = '2023-04-01' endDateStr = '2024-04-30' # Check if date dateStr is between startDateStr and endDateStr if is_between(dateStr, startDateStr, endDateStr): print("Yes, given Date is Between Two Dates") else: print("No, given Date is Not Between Two Dates")
Output
Yes, given Date is Between Two Dates
Summary
We learned about a way to check If a Date is between Two Dates in Python.
Leave a Reply
You must be logged in to post a comment.