Cron-converter
Cron-converter is a Python library that provides a cron string parser and scheduler. It allows parsing cron expressions from strings or lists and iterating over datetime objects in a cron-like format. It is a transposition of the JavaScript cron-converter library and is currently at version 1.3.1, actively maintained with regular releases.
Warnings
- gotcha The `schedule()` method returns an infinite iterator. To avoid unbounded loops, always use limiting mechanisms like `itertools.islice()` or implement explicit break conditions.
- gotcha For correct handling of Daylight Saving Time (DST) and timezone conversions, initialize your `Cron` instance's `schedule` method with a timezone-aware `datetime` object or specify a `timezone_str`. By default, `schedule` starts with a UTC datetime.
- deprecated `cron-converter` has been recommended as a replacement for the `croniter` library, which is set to be decommissioned. Users migrating from `croniter` should be aware of API differences.
- gotcha Constructor options like `output_weekday_names`, `output_month_names`, and `output_hashes` are available to modify the output format of the cron string. These are `false` by default.
Install
-
pip install cron-converter
Imports
- Cron
from cron_converter import Cron
Quickstart
from cron_converter import Cron
from datetime import datetime
from itertools import islice
import dateutil.tz # Dependency for timezone-aware operations
# Example 1: Basic cron parsing and iteration (UTC)
cron_expression_str = '*/10 9-17 * * MON-FRI'
cron_instance = Cron(cron_expression_str)
print(f"Cron expression: {cron_instance.to_string()}")
print(f"Cron list representation: {cron_instance.to_list()}")
# Get a schedule iterator, starting from a specific datetime
start_time = datetime(2026, 4, 14, 8, 0, 0, tzinfo=dateutil.tz.UTC)
# The schedule iterator is infinite, use islice or explicit breaks
schedule = cron_instance.schedule(start_time)
print(f"Next 5 scheduled times after {start_time}:")
for i, next_run in enumerate(islice(schedule, 5)):
print(f" {i+1}: {next_run}")
# Example 2: With constructor options (outputting names)
cron_with_names = Cron('*/5 9-17 * 1-3 MON-FRI', {
'output_weekday_names': True,
'output_month_names': True
})
print(f"Cron with names: {cron_with_names.to_string()}")