Pythonのdatetimeで月間の日数を計算する

月間の日数を計算するPythonコード。

なんか前にも書いた気がするけど、もうちょっと綺麗に書いたので載せ直しておく。

from datetime import datetime, timedelta

def get_ndays(year: int, month: int) -> int:
    if (month > 12) or (month < 1):
        raise ValueError('month must be between 1 and 12.')
    nextmonth = 1 if month + 1 > 12 else month + 1
    nextyear  = year+1 if month + 1 > 12 else year
    dt = datetime(nextyear, nextmonth, 1)
    dt = dt - timedelta(days=1)
    return dt.day

get_ndays(year=2021, month=9)

要はdatetimeを翌月の頭に指定しておいて1日戻すと月末になるので、そこのdatetime.dayを取ってきてるだけ。