I am using rrule from python-dateutil 2.8.2 in python 3.10 to generate datetimes.
I can't figure out how to create a rrule that creates outputs for only even week numbers.
It seems like the "byweekno" parameter might be able to do this, but I haven't been able to find any examples that explain how to only output from even weeks.
Edit 1: Unfortunately there is no guarantee that my "dtstart" is in an even week, which means that using "interval" would not be helpful as far as I can tell.
CodePudding user response:
This construct should work:
In [23]: list(rrule(freq=WEEKLY, interval=2, count=5))
Out[23]:
[datetime.datetime(2022, 8, 6, 15, 45, 35),
datetime.datetime(2022, 8, 20, 15, 45, 35),
datetime.datetime(2022, 9, 3, 15, 45, 35),
datetime.datetime(2022, 9, 17, 15, 45, 35),
datetime.datetime(2022, 10, 1, 15, 45, 35)]
You will just need to kick it off on whatever (even) week you want by setting the dtstart
argument to the correct date. That, is described in this answer:
Datetime from year and week number
CodePudding user response:
After thinking it over some more, I used the following rule:
list(rrule.rrule(freq=WEEKLY, byweekday=MO, byhour=12, byweekno=range(2, 54, 2), dtstart=datetime.datetime(year=2023, month=3, day=11), until=datetime.datetime(year=2023, month=5, day=31)))
... to create biweekly outputs:
[datetime.datetime(2023, 3, 20, 12, 0), datetime.datetime(2023, 4, 3, 12, 0), datetime.datetime(2023, 4, 17, 12, 0), datetime.datetime(2023, 5, 1, 12, 0), datetime.datetime(2023, 5, 15, 12, 0), datetime.datetime(2023, 5, 29, 12, 0)]
Using range to create a list of the 26 even week numbers feels a bit brute force for my taste, so I would love it if somebody else could suggest a more elegant approach.