LoginSignup
1
0

More than 3 years have passed since last update.

calendarライブラリを利用して月終わりの日程を取得する

Posted at

API開発の過程で手軽に12ヶ月分の月はじめ〜月終わりの日付を取得したいと思い、作ってみました。簡単に試せるように、入力値をYYYYMMで取得して変換できます。需要あるかわかりませんがお好みにカスタマイズしてご利用ください。

import sys
import calendar

print('please indicate you wanna retrieve monthly data')
input_data = input()

# validation
if input_data.isdecimal() == False:
    print('please input only numbers!')
    exit()
elif len(input_data) != 6:
    print('please input in 6 digits(like 202004)!')
    exit()

year = int(input_data[:4])
month = int(input_data[4:6])
first_day = '01'

def lastDayOfMonth(year, month):
    _, last_day = calendar.monthrange(year, month)
    return last_day

# output
def converter(year, month):
    print(f"{year}-{str(month).zfill(2)}-{first_day}, {year}-{str(month).zfill(2)}-{lastDayOfMonth(year, month)}")
    for i in range(0, 11):
        month -= 1
        if month == 0:
            month = 12
            year -= 1
        print(f"{year}-{str(month).zfill(2)}-{first_day}, {year}-{str(month).zfill(2)}-{lastDayOfMonth(year, month)}")

converter(year, month)
# 出力データ(202004と入力した場合)
2020-04-01, 2020-04-30
2020-03-01, 2020-03-31
2020-02-01, 2020-02-29
2020-01-01, 2020-01-31
2019-12-01, 2019-12-31
2019-11-01, 2019-11-30
2019-10-01, 2019-10-31
2019-09-01, 2019-09-30
2019-08-01, 2019-08-31
2019-07-01, 2019-07-31
2019-06-01, 2019-06-30
2019-05-01, 2019-05-31
1
0
1

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
0