5
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Pythonで月初、月末の平日の年月日を取得する

Last updated at Posted at 2021-05-21

概要

月初、月末の平日の年月日を取得するサンプルコード。つまり土日、祝日でない月初日、月末日を取得する。
日本の祝日判定には、jpholidayを使う。
slackなどでの月初、月末の社内通知などにどうぞ。

環境

  • Python 3.7
  • jpholiday==0.1.5
  • pytz==2021.1

サンプルコード

import jpholiday
import datetime
import pytz
import calendar


# 今日の%Y-%m-%d
def fetch_today() -> datetime:
    return datetime.datetime.now(pytz.timezone('Asia/Tokyo')).date()

# 土日、祝日かどうか
def is_holiday(day: datetime) -> bool:
    # day.weekday() => 0=月曜日...5=土曜日、6=日曜日
    return day.weekday() >= 5 or jpholiday.is_holiday(day)

# 月の初日を取得
def first_day(today: datetime) -> datetime:
    return today.replace(day=1)

# 月の末日を取得
def last_day(year, month: datetime) -> datetime:
    day =  calendar.monthrange(year, month)[1]
    return datetime.datetime.strptime(f'{year}-{month}-{day}', '%Y-%m-%d').date()

# 月の平日の初日を取得
def fetch_first_bizdate(day) -> datetime:
    first_date = first_day(day)
    while is_holiday(first_date):
        first_date = first_date + datetime.timedelta(days=1)

    return first_date

# 月の平日の末日を取得
def fetch_last_bizdate(year, month) -> datetime:
    last_date = last_day(year, month)
    while is_holiday(last_date):
        last_date = last_date - datetime.timedelta(days=1)

    return last_date

if __name__ == '__main__':
  # 今日
  today = fetch_today()
  # 月の平日の初日
  first_bizdate = fetch_first_bizdate(today)
  # 月の平日の末日
  last_bizdate = fetch_last_bizdate(today.year, today.month)

  print(f'today: {today}')
  print(f'last_bizdate: {last_bizdate}')
  print(f'first_bizdate: {first_bizdate}')

  # 今日は月の平日の初日 or 末日かどうか
  today in [first_bizdate, last_bizdate]
5
6
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
5
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?