Pythonで指定した年月の末日をdatetime型で作成するには、calendarモジュールを使ってその月の最終日を取得し、それをdatetimeクラスに渡してインスタンスを作成します。以下はその一例です:
import calendar
from datetime import datetime
def get_last_day_of_month(year, month):
# その月の最後の日を取得
last_day = calendar.monthrange(year, month)[1]
# datetimeオブジェクトを作成
return datetime(year, month, last_day)
# 例:2023年11月の末日
end_of_month = get_last_day_of_month(2023, 11)
print(end_of_month)
このコードを実行すると、指定した年月(この例では2023年11月)の末日を含むdatetimeオブジェクトが出力されます。
ちなみに、calendar.monthrange
は最初の曜日(月曜日が0)と、日数を返してくれる意味不明な関数です。