0

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!"
sophros
  • 14,672
  • 11
  • 46
  • 75
user2242044
  • 8,803
  • 25
  • 97
  • 164

2 Answers2

3

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
unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677
0

If you want to keep your code simple, you can use the below code:

import datetime
import time

while True:
    time.sleep(1)
    if datetime.datetime.now().time().strftime("%H:%M:%S")  == '19:00:00':
        print ("it's time!")

Sleep is used to generate only 1 row per 1 second (without this you will print thousands of lines. Also it is worth to convert time to string.

fasola195
  • 11
  • 1