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