Skip to content Skip to sidebar Skip to footer

Python Time Range Validator

I have 2 parameters in DB: start and stop. value for them can be eg 07:00-23:00 or 23:00-07:00 (start after 07, stop after 23 or start after 23, stop after 07) In that time, a sta

Solution 1:

There are two cases: the current time is between given times (clock-wise) or outside (imagine the clock circle):

#!/usr/bin/env python
from datetime import datetime

def in_between(now, start, end):
    if start<end: # e.g., "07:00-23:00"
        returnstart<= now <end
    elif end<start: # e.g., "23:00-07:00"
        returnstart<= now or now <endelse: # start==endreturnTrue # consider it 24hourinterval

now = datetime.now().time()
for date_range in ["07:00-23:00", "23:00-07:00"]:
    start, end= [datetime.strptime(s, "%H:%M").time()
                  for s in date_range.split("-")]
    not_ ='' if in_between(now, start, end) else'not '
    print("{now:%H:%M} is {not_}in between {date_range}".format(**vars()))

Output

02:26isnotin between 07:00-23:0002:26isin between 23:00-07:00

Solution 2:

UPDATE: Based on your update

This looks better, the only thing I'm confused about is your if datetime.now() < endTrig conditional.

Correct me if I'm still misunderstanding you, but your current conditional looks like it reads:

ifnow() is before endTrigger:
  - if status is 1, we are good, stay on
  - if status is 0, turn on
  - if status is anything else (but cant it only be 1or0?):
    * if status is 1 ... (but wait, we already checked forthis above!)
    * if status is 0 ... (ditto, these two checks will never trigger)
    * otherwise, force off
ifnow() is after endTime:
  - some logging (shouldnt this be where we turn off?)

You mentioned status must be 0 or 1. Based on that I would expect your conditional to look something like:

.
. [start/end setup stuff]
.
# If we haven't reached end time yetif datetime.now() < endTrig:
    # If status is 1, we're already onif curStatus == 1:
        log('Already on')
    # If status isn't 1, it must be 0 and we should turn onelse:
        log('Turn on')
        flipSwitchOn()

# If we have passed the end timeelse:
    # If we're on, time to turn offif curStatus == 1:
        log('Turning off')
        flipSwitchOff()
    # If its not 1 it must be 0, we're off, stay offelse:
        log('Already off')

Post a Comment for "Python Time Range Validator"