I'm trying to find with a dateutil.rrule the first match before a given datetime.
ATTEMPT 1 :
My first attempt was :
dtstart = datetime(2010, 1, 1, 0, 00)
myRule = rrule(freq=WEEKLY, dtstart=dtstart)
result = myRule.before(dtstart)
It doesn't work, the variable result will be equal to None.
If I'm right, when you execute the method before of an rrule, you will unfortunatelly search after the datetime passed to parameter dtstart.
So basically, my previous code can be represent as that kind of timeline :
[zone A][TARGET][zone B][dtstart][zone C]
And in that timeline, only the [zone C] is parsed, so my target is never found.
ATTEMPT 2 :
My second attempt kind of works but is realy ugly... The purpose is to shift the [dtstart] before the [TARGET] to get a timeline that looks like that :
[zone A][dtstart][zone B][TARGET][zone C]
To do so, I have to figure out a dtstart that is, for sure, before the target and not that far of it to avoid performance issue. So the [zone B] must exists but must be as short as possible.
seekdt = datetime(2010, 1, 1, 0, 00)
startdt = seekdt - timedelta(days=7) # While my rrule.freq is WEEKLY and the interval is 1 (default), I'm sure that my startdt will be before my target if I shift it by 7 days
myRule = rrule(freq=WEEKLY, dtstart=startdt)
result = muRule.before(seekdt)
As I said, that solution is really ugly... Also it can be hard to define the best shift if I have a much more complexe rrule or rruleset.
The best solution but that actually doesn't seams to exists... :'( :
If rrule could take a dtend instead of a dtstart, that would have been perfect. I could just do something like that :
dtstart = datetime(2010, 1, 1, 0, 00)
myRule = rrule(freq=WEEKLY, dtend=dt)
result = muRule.before(dt)
The question :
Seams odd to me if there isn't any easy feature to do it. Is there any elegant way to reach my goal ? Is my attempt 2 the best solution ?
In other words (the same problematic but as an exercise):
How would you do to find the last Friday the 13th that was in February (based on today) ?