Pythonで月末月初の営業日を求める
月初の第二営業日みたいなのも求められるようにしています。
import datetime
import calendar
def is_business_day(date):
return date.weekday() < 5 # 5:土、6:日
def get_beginning_of_the_month_business_day(year, month, offset=0):
first_day = datetime.date(year, month, 1)
# print(first_day.strftime("%Y/%m/%d"))
count = 0
while True:
if is_business_day(first_day):
if count >= offset:
return first_day
else:
count = count + 1
first_day = first_day + datetime.timedelta(days=1)
def get_end_of_the_month_business_day(year, month, offset=0):
monthrange = calendar.monthrange(year, month)
day = monthrange[1]
last_day = datetime.date(year, month, day)
# print(last_day.strftime("%Y/%m/%d"))
count = 0
while True:
if is_business_day(last_day):
if count >= offset:
return last_day
else:
count = count + 1
last_day = last_day - datetime.timedelta(days=1)
if __name__ == "__main__":
now = datetime.datetime.now()
print(now.strftime("%Y-%m-%d"))
print(get_beginning_of_the_month_business_day(now.year, now.month, 0))
print(get_end_of_the_month_business_day(now.year, now.month, 0))
print(get_beginning_of_the_month_business_day(now.year, 5, 1))
print(get_end_of_the_month_business_day(now.year, 5, 1))
$ python business_day.py
2021-04-19
2021-04-01
2021-04-30
2021-05-04
2021-05-28
is_business_day()
の中に処理を追加すれば祝日加味とかもできるはず。
ディスカッション
コメント一覧
まだ、コメントがありません