您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

Python脚本每天在同一时间做某事

Python脚本每天在同一时间做某事

您可以这样做:

from datetime import datetime
from threading import Timer

x=datetime.today()
y=x.replace(day=x.day+1, hour=1, minute=0, second=0, microsecond=0)
delta_t=y-x

secs=delta_t.seconds+1

def hello_world():
    print "hello world"
    #...

t = Timer(secs, hello_world)
t.start()

这将在第二天凌晨1点执行一个函数(例如hello_world)。

正如@PaulMag所建议的,更一般而言,为了检测是否必须由于该月末到达而必须重置该月的某天,在此上下文中y的定义应为:

y = x.replace(day=x.day, hour=1, minute=0, second=0, microsecond=0) + timedelta(days=1)

使用此修复程序,还需要将timedelta添加到导入中。其他代码行保持相同。因此,还使用total_seconds()函数的完整解决方案是:

from datetime import datetime, timedelta
from threading import Timer

x=datetime.today()
y = x.replace(day=x.day, hour=1, minute=0, second=0, microsecond=0) + timedelta(days=1)
delta_t=y-x

secs=delta_t.total_seconds()

def hello_world():
    print "hello world"
    #...

t = Timer(secs, hello_world)
t.start()
python 2022/1/1 18:41:12 有322人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶