0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

残プロ 第-8回 ~pythonで第N曜日を計算する~

Last updated at Posted at 2021-06-09

このプログラムではこんなことします

  • 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さんのサイトを参考にさせていただきました.

0
1
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?