YYMM入力から当月、先月、先々月(GUI)

投稿者: | 2022-12-24

import PySimpleGUI as sg
import sys
from datetime import datetime
from dateutil.relativedelta import relativedelta

"""
USAGE:import
from mylib.get_yymm import get_yearmonth
"""

def get_yearmonth(message, title=None):
    """GUIで文字列YYMMからdatetimeを取得.

    Parameters:
    ------------------------
    message:    str
                popupの本文
    title:      str
                popupのタイトル
    
    Returns:
    ------------------------
    datetime
    """
    while True:
        yymm = sg.popup_get_text(message, title=title)
        if yymm == '0':
            abort_process()
        try:
            yymm_dt = datetime.strptime(yymm, '%y%m')
            sg.popup(f'{yymm} で登録しました')
            return yymm_dt
        except Exception as ex:
            print(ex)
            sg.popup_error('Please enter the correct characters')
      

def abort_process():
    sg.popup(f'処理を中断します:')
    sys.exit()

start_month_dt = get_yearmonth('YYMM(半角数字)を入力ください(0:中断)', title='交付金申請の報告月')
last_month_dt = start_month_dt + relativedelta(months=-1)
two_months_ago_dt = start_month_dt + relativedelta(months=-2)

print(f'報告月:{start_month_dt}-->{start_month_dt.strftime("%Y%m")}')
print(f'先月:{last_month_dt}-->{last_month_dt.strftime("%Y%m")}')
print(f'先々月:{two_months_ago_dt}-->{two_months_ago_dt.strftime("%Y%m")}')