pythonで対象日付を動的に取るサンプル
はい、いまだにpythonに慣れないで四苦八苦(ほとんど触らないから)
ということで、メモ程度に記載。
はい、いまだにpythonに慣れないで四苦八苦(ほとんど触らないから)
ということで、メモ程度に記載。
要件
毎月1日〜15日に実行=前月の16日〜月末
毎月16日〜月末に実行=当月の1日〜15日
引数指定したら、その対象日(from, to両方指定)
@click.command()入力する日付を、時分秒(マイクロ秒)を全てゼロにすることで丸めている。
@click.option('--from-date', type=click.DateTime(['%Y%m%d']))
@click.option('--to-date', type=click.DateTime(['%Y%m%d']))
@stop_watch('main', logger)
def main(from_date, to_date):
if not from_date and not to_date:
# 対象範囲無指定なので自動設定
from_date, to_date = target_range(datetime.today().replace(hour=0, minute=0, second=0, microsecond=0))
elif not from_date or not to_date:
raise click.ClickException('from_date, to_date は指定するなら両方指定してください!')
def target_range(now):
"""
実行日を与えると集計対象日の組を返します
"""
if now.day < 16: # 1日実行。(2〜15日に実行した場合も)
from_date = now.replace(day=16) - relativedelta(months=1)
to_date = now.replace(day=1) - timedelta(days=1)
else: # 16日実行(17日以降に実行した場合も)
from_date = now.replace(day=1)
to_date = now.replace(day=15)
return from_date, to_date
コメント