今回は「Pythonで特定の年月の曜日の日数を取得する方法」について紹介したいと思います。
import datetime from calendar import monthrange #年月の設定 year = 2023 month = 1 #月末日の取得(youbiにはその年月の1日の曜日が入ります) youbi, lastDay = monthrange(int(year), int(month)) #日曜日カウント用変数 sundayCount = 0 saturdayCount = 0 fridayCount = 0 thursdayCount = 0 wednsdayCount = 0 tuesdayCount = 0 mondayCount = 0 #ループ処理 for dayNum in range(lastDay): #日曜日の場合、カウントアップ if datetime.datetime(int(year), int(month), dayNum + 1).weekday() == 6: sundayCount += 1 elif datetime.datetime(int(year), int(month), dayNum + 1).weekday() == 5: saturdayCount += 1 elif datetime.datetime(int(year), int(month), dayNum + 1).weekday() == 4: fridayCount += 1 elif datetime.datetime(int(year), int(month), dayNum + 1).weekday() == 3: thursdayCount += 1 elif datetime.datetime(int(year), int(month), dayNum + 1).weekday() == 2: wednsdayCount += 1 elif datetime.datetime(int(year), int(month), dayNum + 1).weekday() == 1: tuesdayCount += 1 elif datetime.datetime(int(year), int(month), dayNum + 1).weekday() == 0: mondayCount += 1 #日曜日の数を表示 print('日曜日',sundayCount) print('土曜日', saturdayCount) print('金曜日', fridayCount) print('木曜日', thursdayCount) print('水曜日', wednsdayCount) print('火曜日', tuesdayCount) print('月曜日', mondayCount)
コメント