taichino / croniter

croniter is a python module to provide iteration for datetime object.
http://github.com/taichino/croniter
387 stars 105 forks source link

Add a date matching method #54

Closed julienvienne closed 4 years ago

julienvienne commented 8 years ago

Hello, This is mostly a feature request... Would it be possible to implement a simple function that would tell if a datetime match a crontab expression ? In some cases, datetime given in crontiter constructor exactly match the crontab expression. Il that case the behavior needed for the get_next() or get_prev() methods may be ambiguous. I would like to be able to code something like this :

iter = croniter("0 0 * * *", dtetime)
if iter.match(dtetime):
   next = dtetime
else:
   next = iter.get_next()

Do you think such a feature could be possible ?

Best regards,

kiorky commented 5 years ago

I see the point, for now i dont know how to implement it correctly, specially related to ressources usage;

We would need for a specific datetime compute all the combinations of hours of a day, with that cron, that spend on the years previous that datetime, in a bruteforce way. That's a bit desastrous i think.

pomdtr commented 5 years ago

Maybe a incomplete solution but i usually run :

def match(date, cron_expression):
    date_shifted = date + timedelta(microseconds=1)
    return croniter(cron_expression, date, ret_type=datetime).get_prev() == date
samwedge commented 4 years ago

I was just about to raise an issue about the same thing. I guess subtracting 1 microsecond is safe, since the granularity of cron is 1 second. But just for info, I have solved this in the past by doing the following. This negates the need to subtract an arbitrary unit of time.

def match(cron_expression, date):
    iter = croniter(cron_expression, date)
    iter.get_prev()
    return iter.get_next(datetime) == date
kiorky commented 4 years ago

[0.3.32]https://pypi.org/project/croniter/] is out !