Q:

How can I set up the time to run in Python Script

I am trying to run my python script to run on specific time.
For example, I don't want it to run at 12 AM to 3 AM. 
So it will only run 3AM to 11PM and sleep for 3 hours and run again after 3 AM.
I don't want to kill the PID if it runs while it reached 12 AM.. I want it to finish and go to sleep if the time is between 12 AM and 3 AM..
for Shell Script:
 while true
 do
       curr_time=`date +"%H%M%S"`
       if [ $curr_time -ge 235000 -a $curr_time -le 030000 ]
       then
            sleep 12000 
            #Going to check time before 12AM so that it can stop before 12
            #Sleep for little more than 3hours since it might stop before 3AM
       else
            break;
       fi
 done`

But main question is.. I can't think of a way to do this in python. 
Also, is there a way to set the sleeping time automatically wake up at 3AM? instead of me setting how long it should sleep? 

A:

Ideally you should be using an existing scheduler, but if you must sleep yourself, the datetime module makes it fairly straightforward:
import datetime
while 1:
    now = datetime.datetime.now()
    if now.hour < 3:
        at_3 = datetime.datetime.combine(datetime.date.today(),
                                         datetime.time(3))
        to_sleep = (at_3 - now).seconds
        time.sleep(to_sleep)

    # do the work ...

