Question

I need to create RRULE string with BYDAY parameter, from my date value.

Is there any natural way to do it?

I wrote this utility code for this purpose:

import calendar

fweek_fday, mdays = calendar.monthrange(date.year, date.month)
# Get weekday of first day and total days in current month
mweeks = ((mdays+fweek_fday-1)//7)+1
# Get total weeks in current month
mday, wday = date.day, date.weekday()
# Get current day of month and current day as day of a week
week_days = ['MO', 'TU', 'WE', 'TH', 'FR', 'SA', 'SU']
week = ((mday+fweek_fday-1)//7)+(1 if wday>=fweek_fday else 0)
# Get current week no
week = -1 if week == mweeks else week
wday = week_days[wday]

output = "BYDAY=%d%s" % (week, wday)
Was it helpful?

Solution

as you said in comment there is no module that I've found yet to make a rule out from a set of constraints. should it be possible for you, you may consider the RDATE rather than going for the BYDAY.

another option for you would be:

import datetime
(y,w,d ) = date.isocalendar()
#w will be the iso week number, d the day of week
(y2,wb,d2) = datetime.datetime(date.year,date.month,1).isocalendar()
wkcount = 1 if d>=d2 else 0
# you need to account whether your date is a weekday after the one of the first of the month or not
print "BYDAY=%d%s"%(w-wb+wkcount,date.strftime("%a").upper()[0:2])

however be careful should your rule also include WKST

OTHER TIPS

The natural way to do this—unless you're writing an iCalendar library—is to use a pre-existing iCalendar library that has methods for dealing with recurrence rules, etc., as objects instead of doing string parsing and generation.

It's possible that there is no such library, in which case you're out of luck. But the first thing you should do is look for one.

A quick search at PyPI turns up many possibilities. The first one, iCalendar, is described as "a parser/generator of iCalendar files", which sounds like a good candidate. Skim the docs, or just pip install it and play with it, to see if it can do what you want.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top