我需要根据我的日期值创建带有BYDAY参数的RRULE字符串。
有什么自然的方法可以做到吗?
我为此目的编写了此实用程序代码:
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)
最佳答案
正如您在评论中所说,我还没有找到可以从一组约束中排除规则的模块。 如果可能的话,您可以考虑 RDATE 而不是 BYDAY。
您的另一个选择是:
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])
但是,如果您的规则还包括 WKST,请务必小心
关于python - 如何将日期格式化为 BYDAY(iCalendar 规范),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13167150/