Question

Best practice to get if a time within a given time frame.

Current hour: 22:00
Timeframes (start, end time of shifts):

00:00 - 08:00
04:00 - 12:00
08:00 - 16:00
12:00 - 20:00
16:00 - 00:00
20:00 - 04:00

Using the logic:

if currentHour >= startHour and currentHour <= endHour:
    ...

Doesn't really work since it will not be less then 04:00 if the time is 22:00. Using OR will not work either since then 22 will be more then 00:00 and that's not right.

Argh I don't know if it's the lack of caffeine or what but i just can't wrap my head around it...

Was it helpful?

Solution

You have to remember that, if the endHour < startHour, it's actually on a different day, ie. 24 hours later than it says. Likewise, for an hour to be in this range, it could be on either day, so if it's < startHour, it could be on the next day.

if currentHour < startHour:
   currentHour += 24
if endHour < startHour:
   endHour += 24

if currentHour >= startHour and currentHour <= endHour:
   //...code

OTHER TIPS

If 00:00 is the end of timeframe, make it 24:00. This would solve make your if statement work in the expected manner.

My Bad : do this

if currentHour >= startHour and currentHour <= endHour or currentHour <= startHour and currentHour >= endHour :

Edit: This generates the following,

print cur, start, end, logic1, logic2
23 8 0 False False
23 20 12 False False
23 0 20 False False
23 12 4 False False
23 8 16 False False
23 16 8 False False
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top