42

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?

Krumelur
  • 31,081
  • 7
  • 77
  • 119
  • possibile duplicate of [Parse a cron entry in Python](http://stackoverflow.com/questions/1511854/parse-a-cron-entry-in-python), have a look at [python-crontab](http://pypi.python.org/pypi/python-crontab/) – Paolo Moretti Sep 12 '11 at 15:30
  • 1
    Possibly asked before: http://stackoverflow.com/questions/4190997/is-there-a-python-module-to-get-next-runtime-from-a-crontab-style-time-definition – John Giotta Sep 12 '11 at 15:31
  • python-crontab was one of the first solutions I investigated, and it does not have the functionality to get the dates. – Krumelur Sep 13 '11 at 09:09
  • 1
    Now that I know what I'm looking for, I believe this is more a duplicate of http://stackoverflow.com/questions/4610904/calculate-next-scheduled-time-based-on-cron-spec – Krumelur Sep 13 '11 at 09:19

2 Answers2

81

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)
HAL
  • 2,011
  • 17
  • 10
  • 2
    This exactly what I need, and I need the get_prev function which is there. Thanks! – Krumelur Sep 13 '11 at 09:18
  • 3
    +1 for croniter. I was looking for a Python equivalent of Java's [Spring CronTrigger](http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/scheduling/support/CronTrigger.html). I find the latter's API a bit more natural, although I don't really like either. I would rather favor a stateless and immutable object instead, e.g. `cronExpr = CronExpression.compile("0 0 * * * "); datetime = cronExpr.next(datetime);`. – Pierre D Nov 07 '15 at 01:05
2

Maybe you can use this module:

http://code.activestate.com/recipes/577466-cron-like-triggers/

I used that module for making an user-space cron in Python and it works very well. This module can handle crontab-like lines.

Diego Navarro
  • 9,316
  • 3
  • 26
  • 33