pycron: Cron-like Parser
pycron is a simple Python library for parsing cron-like expressions and determining if a given datetime matches the specified conditions. It supports standard cron formats, day names, and step values. The current version is 3.2.0, and the library is actively maintained with several releases per year.
Warnings
- breaking Version 3.0.0 dropped support for Python 2.7 and Python 3.4. Users on these older Python versions must remain on `pycron < 3.0.0`.
- breaking Version 3.1.0 included updates to the DOM (Day of Month) and DOW (Day of Week) parsing logic. While intended for correctness, this might subtly change the interpretation of certain complex or edge-case cron expressions, potentially leading to different match outcomes.
- gotcha pycron supports both timezone-aware and naive datetime objects. However, mixing them or not consistently handling timezones can lead to unexpected matches, particularly when cron expressions refer to specific times (e.g., '0 0 * * *' for midnight). The library itself does not perform timezone conversions.
- gotcha pycron 3.x strictly requires Python versions >=3.9 and <4.0. Attempting to install or run on Python 3.8 or older, or Python 4.0 and newer (when released) without explicit support, will result in installation failures or runtime errors.
Install
-
pip install pycron
Imports
- is_now
from pycron import is_now
- has_been
from pycron import has_been
Quickstart
import datetime
from pycron import is_now, has_been
# Check if current time (or a specific datetime) matches a cron string
# This example checks if it's currently every minute
matches_every_minute = is_now('* * * * *')
print(f"Matches every minute (current time): {matches_every_minute}")
# Check for a specific time, e.g., 9:30 AM every weekday
specific_dt = datetime.datetime(2023, 10, 26, 9, 30, 0) # Thursday
matches_specific_time = is_now('30 9 * * 1-5', specific_dt)
print(f"Matches 9:30 AM on a weekday (2023-10-26 09:30): {matches_specific_time}")
# Using has_been (anacron style)
# Check if '0 0 * * *' (midnight) has occurred since an hour ago
now = datetime.datetime.now()
one_hour_ago = now - datetime.timedelta(hours=1)
midnight_occurred = has_been('0 0 * * *', one_hour_ago, now)
print(f"Midnight occurred between {one_hour_ago.strftime('%H:%M')} and {now.strftime('%H:%M')}: {midnight_occurred}")