Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - Working out if time now is between two times

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:

  • Difference between two time intervals?

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!

like image 899
dalgibbard Avatar asked Dec 11 '13 11:12

dalgibbard


People also ask

How do you check if time is within a certain range in Python?

Therefore, you can use the expression start <= current <= end to check if a current time falls into the interval [start, end] when assuming that start , end , and current are datetime objects.

What does %% time mean in Python?

%%time is a magic command. It's a part of IPython. %%time prints the wall time for the entire cell whereas %time gives you the time for first line only. Using %%time or %time prints 2 values: CPU Times.


2 Answers

Kevron's post actually helped solve my issue. My requirement was slightly different where I was passing strings. My version looks like this:

def is_hour_between(start, end):
    # Time Now
    now = datetime.datetime.now().time()
    # Format the datetime string
    time_format = '%Y-%m-%d %H:%M:%S'
    # Convert the start and end datetime to just time
    start = datetime.datetime.strptime(start, time_format).time()
    end = datetime.datetime.strptime(end, time_format).time()

    is_between = False
    is_between |= start <= now <= end
    is_between |= end <= start and (start <= now or now <= end)

    return is_between

check = is_hour_between('2021-04-07 08:30:00', '2021-04-07 04:29:00') #spans to the next day
print("time check", check) # result = True

Hope this helps someone struggling with string times.

like image 82
jAC Avatar answered Nov 16 '22 03:11

jAC


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")
like image 25
jfs Avatar answered Nov 16 '22 03:11

jfs