Cron Validator
cron-validator is a Python library providing tools for validating Unix cron expressions, matching specific datetimes against a cron pattern, and generating a sequence of datetimes that fulfill a given cron expression. It also includes a `CronScheduler` for simple task scheduling. Currently at version 1.0.8, the library receives regular, minor updates primarily for bug fixes and feature enhancements, such as extended cron rule support.
Warnings
- gotcha The library supports 'partially extended rules based on the Amazon EventBridge rule set' (from v1.0.6), which means its cron dialect might differ from strict Unix cron or Quartz cron standards. Always verify specific expressions against the library's implementation. For example, AWS EventBridge cron expressions do not support seconds.
- gotcha The `CronScheduler` is provided for repetitive tasks, but its sample usage often involves a blocking `while True` loop. This design is not suitable for asynchronous applications or long-running processes without external event loop integration (e.g., `asyncio`, `APScheduler`).
- deprecated Prior to v1.0.7, the library did not support month names (e.g., `JAN`, `FEB`) or day of week names (e.g., `MON`, `TUE`) in cron expressions. Using such names in earlier versions would have resulted in validation failures.
- breaking In versions prior to 1.0.1, the `get_execution_time` method might not have rounded execution datetimes to the minute level, potentially returning datetimes with non-zero seconds or microseconds.
Install
-
pip install cron-validator
Imports
- CronValidator
from cron_validator import CronValidator
- CronScheduler
from cron_validator import CronScheduler
- str_to_datetime
from cron_validator.util import str_to_datetime
Quickstart
from datetime import datetime
from cron_validator import CronValidator
from cron_validator.util import str_to_datetime
# 1. Validate a cron expression
assert CronValidator.parse('* * * * *') is not None # Valid Unix cron
assert CronValidator.parse('*/61 * * * *') is None # Invalid minute (max 59)
# 2. Match a datetime with a cron expression
dt_str = '2019-04-23 01:00'
dt = str_to_datetime(dt_str)
assert CronValidator.match_datetime('* * * * *', dt) is True
assert CronValidator.match_datetime('0 * * * *', dt) is False # Does not match minute 0
# 3. Generate matching datetimes between two dates
from_dt_str = '2026-04-11 10:00'
to_dt_str = '2026-04-11 12:00'
from_dt = str_to_datetime(from_dt_str)
to_dt = str_to_datetime(to_dt_str)
print(f"Next executions for '0 * * * *' between {from_dt_str} and {to_dt_str}:")
for execution_dt in CronValidator.get_execution_time(
'0 * * * *',
from_dt=from_dt,
to_dt=to_dt
):
print(execution_dt)
# Expected output for the example above:
# 2026-04-11 11:00:00
# 2026-04-11 12:00:00