pythoncron

Parsing crontab-style lines


I need to parse a crontab-like schedule definition in Python (e.g. 00 3 * * *) and get where this should have last run.

Is there a good (preferably small) library that parses these strings and translates them to dates?


Solution

  • Updated 2025-03-07 to recommend cron-converter instead of croniter since croniter is set to be decommissioned:

    Perhaps the Python package cron-converter suits your needs.

    Usage example:

    >>> import cron_converter
    >>> import datetime
    >>> now = datetime.datetime.now()
    >>> cron = cron_converter.Cron('45 17 */2  * *')
    >>> schedule = cron.schedule(now)
    >>> schedule.next()
    datetime.datetime(2025, 3, 7, 17, 45)
    >>> schedule.next()
    datetime.datetime(2025, 3, 9, 17, 45)
    >>> schedule.next()
    datetime.datetime(2025, 3, 11, 17, 45)
    

    Original answer from 2011:

    Perhaps the python package croniter suits your needs.

    Usage example:

    >>> import croniter
    >>> import datetime
    >>> now = datetime.datetime.now()
    >>> cron = croniter.croniter('45 17 */2  * *', now)
    >>> cron.get_next(datetime.datetime)
    datetime.datetime(2011, 9, 14, 17, 45)
    >>> cron.get_next(datetime.datetime)
    datetime.datetime(2011, 9, 16, 17, 45)
    >>> cron.get_next(datetime.datetime)
    datetime.datetime(2011, 9, 18, 17, 45)