Python使用cron表达式

本文介绍了如何使用Python的croniter库计算两个cron表达式对应的时间差,以及在`say_hello`函数中展示cron表达式的验证和执行。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

# -*- coding: utf-8 -*-

from croniter import croniter
from datetime import datetime, timedelta


def get_timedelta(base_cron=None, parent_cron=None, days=None):
    base_cron = '00 04 * * *' if base_cron is None else base_cron
    parent_cron = '30 01 * * *' if parent_cron is None else parent_cron
    days = 0 if days is None else days

    now = datetime.now()
    base_day = datetime(now.year, now.month, now.day)
    parent_day = base_day + timedelta(days=days)

    base_iter = croniter(base_cron, base_day)
    parent_iter = croniter(parent_cron, parent_day)

    return base_iter.get_next(datetime) - parent_iter.get_next(datetime)


def say_hello():
    # every 5 minutes
    cron = '*/5 * * * *'

    # 验证cron表达式
    is_valid = croniter.is_valid(cron)
    print(is_valid)
    # True

    # 执行计划
    base = datetime(2010, 1, 25, 4, 46)

    iter = croniter(cron, base)

    print(iter.get_next(datetime))  # 2010-01-25 04:50:00
    print(iter.get_next(datetime))  # 2010-01-25 04:55:00
    print(iter.get_next(datetime))  # 2010-01-25 05:00:00



if __name__ == '__main__':
    base = '00 04 * * *'
    parent = '00 3 * * *'
    r = get_timedelta(base, parent, 0)
    print(r)  # 1:00:00
    print(type(r))  # <class 'datetime.timedelta'>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值