Want to check whether two times falls in between to another to time
Checking time is between start=2 pm
and end=3 pm
ex :1
t1=12 PM
T2=2.30 PM
here 0.5 hours
falls in that time
ex :2
t1=2.0 pm
t2=4 pm
here 1 hours
fall in that time
ex : 3
t1=12
t2=5pm
here 2 hours
fall in that time
I want the code to check whether t1 and t2 falls in between start and end
CodePudding user response:
Looks like that should be something like this
from datetime import datetime, timedelta
def _range(t1, t2):
t1 = datetime.strptime(t1, '%I %p')
t2 = datetime.strptime(t2, '%I %p')
if start <= t1 <= end and start <= t2 <= end:
return True
else:
return False
So now
_range('12.30 PM', '2.30 PM')) is True
_range('12 PM', '5 PM')) is False
_range('2.30 PM', '4 PM')) is True
CodePudding user response:
Correct me if I am wrong since I got confused by your question. But based on how I understand it, you simply want to know whether two times fall in between two other times.
Try to use the DateTime module in Python like this:
from datetime import datetime, time
# Start time
start = time(hour=14, minute=0) # 2 PM
# End time
end = time(hour=15, minute=0) # 3 PM
# Check if time1 falls in the range
time1 = time(hour=12, minute=0) # 12 PM
if start <= time1 <= end:
print("Time1 falls in the range")
else:
print("Time1 does not fall in the range")
# Check if time2 falls in the range
time2 = time(hour=14, minute=30) # 2:30 PM
if start <= time2 <= end:
print("Time2 falls in the range")
else:
print("Time2 does not fall in the range")
# Check if time3 falls in the range
time3 = time(hour=16, minute=0) # 4 PM
if start <= time3 <= end:
print("Time3 falls in the range")
else:
print("Time3 does not fall in the range")
This code will check whether each of the three times (time1, time2, and time3) falls in the range between start and end. The output will be:
Time1 does not fall in the range
Time2 falls in the range
Time3 does not fall in the range