pythonicalendarrfc2445rfc5545

How format date into BYDAY (iCalendar specification)


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)

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