Scheduling a Python program to sleep within a given time period
Question: 
    while True:
          now = datetime.datetime.now();
          if now.hour >= 22 and now.hour < 3:
             print "sleep"
             sleep_at = datetime.datetime.combine(datetime.date.today(),datetime.time(3))
             sleep_til = (sleep_at - now).seconds
             print sleep_til
             time.sleep(sleep_til)
             print "wake"
          else:
             print "break"
             break
    

This code should make my entire program to go to sleep at 10 PM and wake up at
3 AM. MY question is.. will this work? I tried running it.. but I cannot
change my system/computer Time.. so I cannot check. Reason why I am posting
this question is because my coding is using datetime.date.tday and
datetime.datetime which is calling current date..

Once again.. I want my program to run before 10PM and sleep between 10PM to
3AM and rerun after 3AM..

Can someone check if this is the right way to do it?


Answer: Consider (extra-verbose for clarity):

    
    
    import time, datetime
    
    # Create time bounds -- program should run between RUN_LB and RUN_UB
    RUN_LB = datetime.time(hour=22)     # 10pm
    RUN_UB = datetime.time(hour=3)      #  3am
    
    # Helper function to determine whether we should be currently running
    def should_run():
        # Get the current time
        ct = datetime.datetime.now().time()
        # Compare current time to run bounds
        lbok = RUN_LB <= ct
        ubok = RUN_UB >= ct
        # If the bounds wrap the 24-hour day, use a different check logic
        if RUN_LB > RUN_UB:
            return lbok or ubok
        else:
            return lbok and ubok
    
    
    # Helper function to determine how far from now RUN_LB is
    def get_wait_secs():
        # Get the current datetime
        cd = datetime.datetime.now()
        # Create a datetime with *today's* RUN_LB
        ld = datetime.datetime.combine(datetime.date.today(), RUN_LB)
        # Create a timedelta for the time until *today's* RUN_LB
        td = ld - cd
        # Ignore td days (may be negative), return td.seconds (always positive)
        return td.seconds
    
    
    while True:
        if should_run():
            print("--do something--")
        else:
            wait_secs = get_wait_secs()
            print("Sleeping for %d seconds..." % wait_secs)
            time.sleep(wait_secs)
    

But I do agree that sleeping is not the best way to delay your program
starting. You may look into the task scheduler on Windows or `cron` on Linux.

