2

Note: read my comments on the provided answer, it doesn't work

I have a python program which runs every 5 seconds like this:

def main():
    start_time = time.time()
    while True:
        if not execute_data():
            break
        time.sleep(5.0 - ((time.time() - start_time) % 5.0))

The question is how can I make it run from 7:00 to 23:00 only? I don't want to use my computer resources at times where I'm sure my program won't be helpful...

1 Answers1

0

You can use datetime.datetime.strptime() and datetime.datetime.strftime():

from datetime import datetime
import time

def str_to_time(string):
    return datetime.strptime(string, "%H:%M")

def main():
    start = '7:00'
    end = '23:00'
    while True:
        now = str_to_time(datetime.now().strftime("%H:%M"))
        if str_to_time(end) > now > str_to_time(start) or str_to_time(end) < now < str_to_time(start):
            print('Working...')
            time.sleep(5)

main()
Red
  • 26,798
  • 7
  • 36
  • 58