![見出し画像](https://assets.st-note.com/production/uploads/images/135179941/rectangle_large_type_2_394ab5cce6ac5925c36d06130cab4922.png?width=1200)
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)
![](https://assets.st-note.com/img/1711444054-E41dM5NMz8.png?width=1200)
要はdatetimeを翌月の頭に指定しておいて1日戻すと月末になるので、そこのdatetime.dayを取ってきてるだけ。