LoginSignup
1
3

More than 3 years have passed since last update.

Pythonで月末・月初を取得

Last updated at Posted at 2021-03-29

メジャーな方法は下記2パターン
・カレンダーで最終日を取得して組み合わせる
・翌月の1日前を計算する

翌月の1日前を計算する方が個人的にしっくりくるので書いてみた

from datetime import date,timedelta
#月末は「翌月初日の1日前」として計算する
year = 2021
for month in range(1,13):
  month_first_day = date(year,month,1) #月の初日
  #date関数は月の引数に13以上が入ると1~12に収めろとエラーするので対応
  if month == 12: exec_year = year + 1; next_month = 1
  else: exec_year = year; next_month = month + 1
  next_month_first_day = date(exec_year,next_month,1) #翌月の初日
  month_end_day = next_month_first_day - timedelta(days=1) #月の最終日(翌月の初日-1日)
  print(str(year)+'年'+str(month).zfill(2)+'月の月初='+str(month_first_day))
  print(str(year)+'年'+str(month).zfill(2)+'月の月末='+str(month_end_day))

実行結果

2021年01月の月初=2021-01-01
2021年01月の月末=2021-01-31
2021年02月の月初=2021-02-01
2021年02月の月末=2021-02-28
2021年03月の月初=2021-03-01
2021年03月の月末=2021-03-31
2021年04月の月初=2021-04-01
2021年04月の月末=2021-04-30
2021年05月の月初=2021-05-01
2021年05月の月末=2021-05-31
2021年06月の月初=2021-06-01
2021年06月の月末=2021-06-30
2021年07月の月初=2021-07-01
2021年07月の月末=2021-07-31
2021年08月の月初=2021-08-01
2021年08月の月末=2021-08-31
2021年09月の月初=2021-09-01
2021年09月の月末=2021-09-30
2021年10月の月初=2021-10-01
2021年10月の月末=2021-10-31
2021年11月の月初=2021-11-01
2021年11月の月末=2021-11-30
2021年12月の月初=2021-12-01
2021年12月の月末=2021-12-31
1
3
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
3