このプログラムではこんなことします
- datetimeモジュール,calendarモジュールを使用
- 第N曜日を文字列で受け取り,日にちに変換
- 既に過ぎていた場合は,翌月第N何曜日を計算
サンプル.py
元の文字列は"EveryDay"や"FirstMonday,EverySunday"などです.これを第-7回の関数separateStrで分割し入力しています.
sample.py
import datetime
import calendar
def str2date(str_list):
date_list = []
for s in str_list:
frequency = s[0]
weekday = s[1]
delta = weekday_list.index(weekday) - today.weekday()
if frequency == "Every":
if weekday == "Day":
date = today
else:
if delta < 0:
delta += 7
date = today + datetime.timedelta(days=delta)
else:
nth = frequency_list.index(frequency) + 1
weekday_first, _ = calendar.monthrange(year=today.year, month=today.month)
day = 7 * (nth-1) + (weekday_list.index(weekday) - weekday_first) % 7 + 1
if day >= today.day:
delta = day - today.day
date = today + datetime.timedelta(days=delta)
else:
weekday_first, _ = calendar.monthrange(year=today.year, month=today.month+1)
day = 7 * (nth-1) + (weekday_list.index(weekday) - weekday_first) % 7 + 1
date = datetime.date(year=today.year, month=today.month+1, day=1) + datetime.timedelta(days=day-1)
date_list.append(date)
return date_list
frequency_list = ['First', 'Second', 'Third', 'Fourth']
weekday_list = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
today = datetime.date.today()
第N曜日の計算にはnkmkさんのサイトを参考にさせていただきました.