Recently, I was working on a project and required to convert cron expression to the total number of executions in one day. There are some libraries in Python that help you to convert cron expressions into human-readable (https://pypi.org/project/cron-descriptor/) texts. However, in my case, I needed to get the total execution.
I found a library (https://pypi.org/project/croniter/) that can give you the exact execution time. I used it to extract the total number of execution in a day.
import croniter import datetime def getTotalNumberOfExecution(cron_str): try: cur_date = datetime.datetime.now() #put the current day (start from 00:00AM) to get its all executions now = datetime.datetime(year=cur_date.year,month=cur_date.month,day=cur_date.day,hour=0,minute=0,second=0) cron = croniter.croniter(cron_str, now) nextdate = cron.get_next(datetime.datetime) count = 0 while nextdate.day <= cur_date.day: #loop over the iterations until it goes to the next day nextdate = cron.get_next(datetime.datetime) count += 1 return count except: if cron_str == "@once": #here you can handle cron strings starts with @ return 1 return 0 # Main # cron_str = "0 * * * *" print(getTotalNumberOfExecution(cron_str))
I hope the above code would help to complete this task. The code is self-explanatory, but if you have any question you can ask me in the comments.