You can use this function which I built for one of my projects. I had this function built at day, hour, minute, second level. I have reduced it for your needs.
def compare_hours(constraint: dict) -> bool:
from datetime import datetime
"""
This is used to compare a given hours,minutes against current time
The constraint must contain a single key and value.
Accepted keys are:
1. before:
eg {"before": "17:30"}
2. after:
eg: {"after": "17:30"}
3. between:
eg: {"between": "17:30, 18:30"}
4. equal:
eg: {"equal": "15:30"}
Parameters
----------
constraint : dict
A dictionary with keys like before, after, between and equal with their corresponding values.
Returns
-------
True if constraint matches else False
"""
accepted_keys = ("before", "after", "between", "equal")
assert isinstance(constraint, dict), "Constraint must be a dict object"
assert len(constraint.keys()) == 1, "Constraint contains 0 or more than 1 keys, only 1 is allowed"
assert list(constraint.keys())[0] in accepted_keys, f"Invalid key provided. Accepted keys are {accepted_keys}"
key = list(constraint.keys())[0]
time_split = lambda x: list(map(int, x.split(":")))
try:
if key == "before":
hours, minutes = time_split(constraint.get(key))
dt = datetime.now()
if dt < dt.replace(hour=hours, minute=minutes):
return True
return False
elif key == "after":
hours, minutes = time_split(constraint.get(key))
dt = datetime.now()
if dt > dt.replace(hour=hours, minute=minutes):
return True
return False
elif key == "between":
dt = datetime.now()
values = constraint.get(key).replace(' ', '').split(",")
assert len(values) == 2, "Invalid set of constraints given for between comparison"
hours, minutes = time_split(values[0])
dt1 = dt.replace(hour=hours, minute=minutes)
hours, minutes = time_split(values[1])
dt2 = dt.replace(hour=hours, minute=minutes)
assert dt2 > dt1, "The 1st item in between must be smaller than second item"
if dt > dt1 and dt < dt2:
return True
return False
else:
hours, minutes = time_split(constraint.get(key))
dt = datetime.now()
if dt == dt.replace(hour=hours, minute=minutes):
return True
return False
except Exception as e:
print(e)
You can reuse the function for your need. For eg:
if compare_hours({"before": "21:00"}) and compre_hours({"after": "18:30"}):
"do something"
This is essentially the same as using the "between" option.