0
votes

I would like to execute a portion of a script at 8 am each day. I have created a simplified test case that has no syntax error, but does not work properly. I think it may be because my if statement is using the time as a string, but it won't compile any other way. What am I doing wrong?

import datetime

while True:
    if datetime.datetime.now().time()  == "19:00:00.000000":
        print "it's time!"
1
Why won't you just use cron? - Tymoteusz Paul
Not familiar with cron, but this should still work - user2242044
Given that you are specific to a millisecond, it may not, as millisecond is very short time and its easy to miss it. Just stick to cron, google can lead you into the right path. - Tymoteusz Paul

1 Answers

3
votes

If you are on a system with cron, then it would be better to set up a cron job. However, your problem is fixable from within Python:

First, as you noted, datetime.datetime.now().time() returns a datetime.time object, not a string:

In [89]: datetime.datetime.now().time()
Out[89]: datetime.time(19, 36, 13, 388625)

Also, although datetime.datetime.now().time() == datetime.time(19, 0) would be valid Python, the chance that you happen to execute time() at just the right moment is very slim since datetime.datetime.now() has microsecond resolution. So it would be better to test if the current time falls within some range.

However, since you only want to run the function once per day, you could instead measure the total number of seconds between now and when you want to run the function and sleep that number of seconds:

import datetime as DT
import time

while True:
    now = DT.datetime.now()
    target = DT.datetime.combine(DT.date.today(), DT.time(hour=8))
    if target < now:
        target += DT.timedelta(days=1)

    time.sleep((target-now).total_seconds())
    # do something