所以我最後一次做這種事情我試圖讓事情時區的具體和幫助了我很多,所以這裏是我想嘗試做。請注意,我在這裏使用了pytz庫,所以你將不得不安裝它。那麼你也可能想把時區改成你所需要的。
from datetime import datetime, time
from time import sleep
import pytz
def get_times():
my_timezone = pytz.timezone('America/Los_Angeles')
last_time = my_timezone.normalize(datetime.now(tz=my_timezone))
midnight = my_timezone.localize(datetime.combine(last_time.date(), time.max))
return last_time, midnight
def main():
last_time, midnight = get_times()
while True:
if last_time > midnight:
# It's passed midnight we need to run it
# do work here...
# now we need to update midnight to todays midnight
last_time, midnight = get_times()
else:
# we shouldn't run the work just update last time
last_time, _ = get_times()
sleep(10)
if __name__ == '__main__':
main()
爲什麼不只是使用cron作業? –
在Python中,邏輯是'&'而不是'&&'。 –