Can someone explain to me, how to check whether a given time in "hh:mm" format falls in between a given range. Say, given time is 10:30 A.M IST and my range is between 10:00 A.M and 11:00 A.M. So given time falls in the range. Is there any package in python to do this in the easiest way? Would be happy if anyone can help with this :)
Asked
Active
Viewed 152 times
-1
-
So your given time is given as such a "hh:mm" string? How is the range given? – no comment Sep 03 '21 at 05:13
-
The question is like this, say you are running a store, if a person buys an item between 10:00 A.M and 11:00 A.M, 5% discount, if he buys between 11:00 A.M and 12:00 P.M, the 7% discount. Like this, there are many cases in the question. – Primph Sep 04 '21 at 06:04
-
So you don't want to tell us. Well, then I can't help you. – no comment Sep 04 '21 at 15:26
-
Please provide enough code so others can better understand or reproduce the problem. – Community Sep 06 '21 at 18:01
1 Answers
0
The simple way is just to use datetime.time
and compare in an if statement:
import datetime
hhmm = "10:30"
current_time = datetime.datetime.strptime(hhmm, "%H:%M").time()
if datetime.time(10) <= current_time <= datetime.time(11):
print("Time is between 10am and 11am")
else:
print("Time is not between 10am and 11am")
The timezone info is removed from the datetime object when .time()
is called on it - if you input a literal time without a timezone, this isn't an issue, while if you do have a timezone then as long as the datetime is transformed (via .astimezone(zoneinfo.ZoneInfo('IST'))
) into the timezone you want, you should just be able to compare with the literal 10am and 11am.

Green Cloak Guy
- 23,793
- 4
- 33
- 53