Python - Working out if time now is between two times

dalgibbard picture dalgibbard · Dec 11, 2013 · Viewed 20.3k times · Source

I'm trying to find the cleanest/most pythonic way of evaluating if "now" is between two times; However; the Start/End times may, or may not, fall across a day boundary- for example (just using simple examples):

onhour=23
onmin=30
offhour=4
offmin=15
timenow = datetime.datetime.now().time()

Doing a straight if START < NOW < END scenario won't work for this!

What I have currently is some code which evaluates if it's currently "NightTime", which looks like this:

def check_time(timenow, onhour, onmin, offhour, offmin, verbose):
    now = datetime.datetime.now()
    now_time = now.time()
    # If we're actually scheduling at night:
    if int(offhour) < int(onhour):
        # Check to see if we're in daylight times (ie. off schedule)
        if datetime.time(int(offhour),int(offmin)) <= now_time <= datetime.time(int(onhour),int(onmin)):
            if verbose == True:
                print("Day Time detected.")
            return False
        else:
            if verbose == True:
                print("Night Time detected.")
            return True
    else:
        if datetime.time(int(onhour),int(onmin)) <= now_time <= datetime.time(int(offhour),int(offmin)):
            if verbose == True:
                print("Night Time detected.")
            return True
        else:
            if verbose == True:
                print("Day Time detected.")
            return False

Apologies if the title doesn't sound like anything new, but having reviewed a few existing answers for similar problems such as:

I noticed that these don't seem to account for instances where the Start and End times occur over a day boundary.

In addition to this; any ideas surrounding adding Day based scheduling would be quite useful too! ie. "for Mon - Fri, turn on at 23:00, off a 04:00" - but managing on and off for a day either side (else; something will be turned on, on Friday, but not be turned off on the Saturday-- and yet, including Saturday means it gets turned back on again at 23!...)

I've considered doing a simple "Turn on at X, sleep for Y" to get around this... but if the script is started up during an "On" cycle, it won't be initiated until the next run... But it seems like the simplest option! :)

I'm hoping there's some sort of awesome module that does all this... :D

Compatibility of Python2.7 - 3.2 is pretty important to me too!

Answer

jfs picture jfs · Nov 12, 2015

To find out whether a given time (no date) is in between given start, end times (the end is not included):

def in_between(now, start, end):
    if start <= end:
        return start <= now < end
    else: # over midnight e.g., 23:30-04:15
        return start <= now or now < end

Example:

from datetime import datetime, time

print("night" if in_between(datetime.now().time(), time(23), time(4)) else "day")