运行Python程序直到指定时间

2024-03-29 11:22:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我想在jupyter笔记本中运行我的程序,这个程序在特定时间停止(例如18:00)。我用while循环和增量索引来编写程序,但最好用时间参数来编写。在

我每天运行上述程序7小时。它必须不停地运行。在

    while(i<500000):
         execute algorithm
         i+=1

但我想像下面这样运行我的程序:

^{pr2}$

Tags: 程序execute参数时间笔记本jupyteralgorithm增量
3条回答
import datetime

while datetime.datetime.now().hour < 18:
    do stuff...

或者

^{pr2}$

导入日期时间

https://docs.python.org/3/library/datetime.html

然后可以使用各种函数(time或timedelta)来设置时间。在

时间现在=日期时间。日期时间() 立即打印时间

您可以创建一个以小时和分钟为参数的函数,并在while循环中执行检查:

import datetime

def proc(h, m):
    while True:
        currentHour = datetime.datetime.now().hour
        currentMinute = datetime.datetime.now().minute
        if currentHour == h and currentMinute == m:
            break
        # Do stuff...

# Function call.
proc(18,0)

相关问题 更多 >