所以我最后一次做这种事情我试图让事情时区的具体和帮助了我很多,所以这里是我想尝试做。请注意,我在这里使用了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中,逻辑是'&'而不是'&&'。 –