Pythonで第何何曜日(第2月曜日など)の日付を取得
Pythonで第何何曜日(第nX曜日: 第2月曜日や第3金曜日など)の日付を取得する方法について説明する。標準ライブラリのcalendarモジュールを利用する。
- 第何何曜日(第nX曜日)の日付を返す関数
- 活用例
反対に任意の日付がその月の第何週の何曜日かを取得したい場合や、最終週の指定曜日の日付を取得したい場合は、以下の記事を参照。
スポンサーリンク
第何何曜日(第nX曜日)の日付を返す関数
第何何曜日(第nX曜日)の日にちを返す関数は以下のように定義できる。datetimeモジュールは後の例で使用するためのもので、この関数に必要なのはcalendarモジュールのみ。
第四引数dow
(day of the week: 曜日)には月曜0
から日曜6
までの整数値で指定する。
その月の初日の曜日と日数を返すcalendar.monthrange()
を使っている。
- 関連記事: Pythonで月の日数・週数を取得
import calendar
import datetime
def get_day_of_nth_dow(year, month, nth, dow):
'''dow: Monday(0) - Sunday(6)'''
if nth < 1 or dow < 0 or dow > 6:
return None
first_dow, n = calendar.monthrange(year, month)
day = 7 * (nth - 1) + (dow - first_dow) % 7 + 1
return day if day <= n else None
source: calendar_day_of_nth_dow.py
結果の例は以下の通り。カレンダーとともに示す。
print(calendar.month(2019, 1))
# January 2019
# Mo Tu We Th Fr Sa Su
# 1 2 3 4 5 6
# 7 8 9 10 11 12 13
# 14 15 16 17 18 19 20
# 21 22 23 24 25 26 27
# 28 29 30 31
#
print(get_day_of_nth_dow(2019, 1, 1, 1)) # 1st Tuesday(1)
# 1
print(get_day_of_nth_dow(2019, 1, 2, 0)) # 2nd Monday(0)
# 14
print(get_day_of_nth_dow(2019, 1, 3, 6)) # 3rd Sunday(6)
# 20
print(get_day_of_nth_dow(2019, 1, 5, 3)) # 5th Thursday(3)
# 31
source: calendar_day_of_nth_dow.py
なお、この関数はあくまでも例で、簡易的なもの。日にちが存在しない場合や曜日が範囲外の数値の場合はすべてNone
を返すようにしているが、用途によってはそれぞれの場合で例外を返すなどの処理を行ったほうがいいかもしれない。
print(get_day_of_nth_dow(2019, 1, 5, 4))
# None
print(get_day_of_nth_dow(2019, 1, 0, 4))
# None
print(get_day_of_nth_dow(2019, 1, 1, 10))
# None
source: calendar_day_of_nth_dow.py
型のチェックもしていないため、浮動小数点数を指定するとおかしな値になるので注意。
print(get_day_of_nth_dow(2019, 1, 2, 1.8))
# 8.8
source: calendar_day_of_nth_dow.py
日にちではなくdatetime.date
(日付: 年月日)を取得したい場合は以下のようにする。この場合は浮動小数点数を指定するとエラー。
def get_date_of_nth_dow(year, month, nth, dow):
day = get_day_of_nth_dow(year, month, nth, dow)
return datetime.date(year, month, day) if day else None
print(get_date_of_nth_dow(2019, 1, 1, 1))
# 2019-01-01
print(get_date_of_nth_dow(2019, 1, 1, 10))
# None
# print(get_date_of_nth_dow(2019, 1, 2, 1.8))
# TypeError: integer argument expected, got float
source: calendar_day_of_nth_dow.py
活用例
上の関数を使った活用例をいくつか示す。
ある年のすべての月の第2月曜日を(月, 日)
のタプルのリストとして取得する例。リスト内包表記を使っている。
- 関連記事: Pythonリスト内包表記の使い方
print([(m, get_day_of_nth_dow(2019, m, 2, 0)) for m in range(1, 13)])
# [(1, 14), (2, 11), (3, 11), (4, 8), (5, 13), (6, 10), (7, 8), (8, 12), (9, 9), (10, 14), (11, 11), (12, 9)]
source: calendar_day_of_nth_dow.py
ある期間の年の成人の日(1月の第2月曜日)の日付を出力する例。
for y in range(2020, 2030):
print(get_date_of_nth_dow(y, 1, 2, 0))
# 2020-01-13
# 2021-01-11
# 2022-01-10
# 2023-01-09
# 2024-01-08
# 2025-01-13
# 2026-01-12
# 2027-01-11
# 2028-01-10
# 2029-01-08
source: calendar_day_of_nth_dow.py
ここではdatetime.date
をそのままprint()
で出力しているが、任意の書式で出力したい場合はstrftime()
メソッドを使えばよい。
スポンサーリンク