1

If I have a function that loops throughout the day denoted by:

def Show()

How can I run it so that at a particular time of the day it won't return anything?

In this instance say 13:50 to 14:20?

Jean123
  • 129
  • 9

2 Answers2

3

If I understand the question correctly, you could just check the time using an if statement:

# import datetime module
from datetime import datetime as dt

# set to time bounds:
lower_bound = dt.time(13, 50)
upper_bound = dt.time(14, 20)

Then just check the time whenever the function runs:

now = dt.now().time()
if lower_bound < now < upper_bound:
     pass
if not (lower_boun < now < upper_bond):
     Show() #that returns something. 

...or just put the if statements into the function itself

Check out this question on now() and this question on comparing time

Answer improved by helpful comments of chepner and 0x5423

Gene Burinsky
  • 9,478
  • 2
  • 21
  • 28
  • 1
    Why use `dt.now` at all? `lower_bound = datetime.time(13, 50)` – chepner Nov 16 '21 at 20:06
  • 1
    Tip: Python lets you [chain](https://docs.python.org/3/reference/expressions.html#comparisons) comparison operators, so you can write that check as `if lower_bound < now < upper_bound:`. – 0x5453 Nov 16 '21 at 20:06
  • @chepner and 0x5453 - thanks for the suggestions. I incorporate them into the answer – Gene Burinsky Nov 16 '21 at 20:11
  • 1
    I would also just negate the condition, rather than use `pass` and an `else` clause. `if not (lower_bound < now < upper_bond): Show()`. Or `if now <= lower_bound or now >= upper_bound: Show()`. – chepner Nov 16 '21 at 20:13
3

schedule is an excellent module for doing all of this. It even runs async without too much work.

https://schedule.readthedocs.io/en/stable/

schedule.every(1).hours.at("06:00").do(show).tag('show', 'guest')

and then stop the schedule at a specific time

schedule.every().day.at("10:30").clear('show')
eatmeimadanish
  • 3,809
  • 1
  • 14
  • 20