You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python定时脚本周一至周五9:20执行故障及节假日添加需求

解决方法

步骤1:定义并格式化节假日列表

先把你的12个节假日字符串转成datetime.date对象,确保和任务使用的印度标准时间(IST)时区一致,避免日期判断出错:

from datetime import datetime
import pytz

IST = pytz.timezone('Asia/Kolkata')
# 替换为你的完整12个节假日
HOLIDAYS = [
    datetime.strptime('25-Mar-2024', '%d-%b-%Y').date(),
    datetime.strptime('29-Mar-2024', '%d-%b-%Y').date(),
    # 继续添加剩余节假日...
]

步骤2:在任务中加入节假日检查

在你的定时任务函数开头添加判断逻辑,若当前IST日期属于节假日则跳过执行:

def your_task():
    # 获取当前IST日期
    current_date = datetime.now(IST).date()
    
    if current_date in HOLIDAYS:
        print(f"跳过节假日 {current_date.strftime('%d-%b-%Y')} 的任务执行")
        return
    
    # 这里写你的实际任务代码
    print(f"任务执行中,当前IST时间:{datetime.now(IST).strftime('%Y-%m-%d %H:%M:%S')}")

步骤3:配置scheduler(以APScheduler为例)

假设你使用的是常用的APScheduler库,配置周一至周五09:20执行任务,同时指定时区为IST:

from apscheduler.schedulers.blocking import BlockingScheduler

if __name__ == '__main__':
    scheduler = BlockingScheduler(timezone=IST)
    # 配置cron规则:周一到周五,9点20分
    scheduler.add_job(
        your_task,
        'cron',
        day_of_week='mon-fri',
        hour=9,
        minute=20
    )
    
    print("调度器启动...")
    try:
        scheduler.start()
    except KeyboardInterrupt:
        scheduler.shutdown()
        print("调度器已停止")

关键注意点

  • 全程使用IST时区处理日期和时间,避免UTC与IST的转换误差导致的日期判断错误。
  • 节假日列表仅需维护HOLIDAYS数组,后续修改或新增节假日直接更新该数组即可。
  • 如果你的scheduler库不是APScheduler,只需保留节假日检查的核心逻辑,适配对应库的任务调度语法即可。

内容的提问来源于stack exchange,提问作者Amingo husk

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.27 12:50:23