下边代码可直接拷贝使用
from datetime import date, datetime, timedelta
# N月後の初日取得
def get_next_n_month_first_day(year:int, month:int, step:int=1):
"""N月後の初日取得
(例: 当月初日 → 2022,10,0 → 結果:2022/10/1)
(例: 翌月初日 → 2022,10,1 → 結果:2022/11/1)
(例: 翌々月初日 → 2022,12,2 → 結果:2023/2/1 )
Args:
year (int): 対象年
month (int): 対象月
step (int, optional): 後N月(翌月:1, 翌々月:2). Defaults to 1.
Returns:
date: 指定月初日
"""
# 初期値
exec_year = year
target_month = month
# 対象年月後のstep月(翌月、翌々月)を取得
for i in range(0,step):
if target_month == 12:
exec_year += 1
target_month = 1
else:
target_month += 1
next_n_month_first_day = date(exec_year, target_month, 1)
return next_n_month_first_day
测试:
>>> from util import date_util as du
>>> du.get_next_n_month_first_day(2022,10,0)
datetime.date(2022, 10, 1)
>>> du.get_next_n_month_first_day(2022,10,1)
datetime.date(2022, 11, 1)
>>> du.get_next_n_month_first_day(2022,12,2)
datetime.date(2023, 2, 1)
# 指定年月の最終日を取得
def get_end_day_of_month(year:int, month:int):
"""指定年月の最終日を取得"""
# 翌月月初日
next_month_first_day = get_next_n_month_first_day(year, month)
# 翌月の初日-1日 → 対象月の最終日
month_end_day = next_month_first_day - timedelta(days=1)
return month_end_day
# 指定月・指定日取得(例:翌月25日)
def get_customize_month_day(year:int, month:int, step:int=1, day:int=1):
"""指定月・指定日取得
(例: 翌月25日 → 2022,10,1,25 → 結果:2022/11/25)
(例: 翌々月31日 → 2022,12,2,31 → 結果:2023/2/28 )
Args:
year (int): 対象年
month (int): 対象月
step (int, optional): 後N月(翌月:1, 翌々月:2). Defaults to 1.
day (int, optional): 指定日. Defaults to 1.
Returns:
date: 指定日付
"""
# 指定月の初日
next_n_month_first_day = get_next_n_month_first_day(year, month, step)
# 指定月の末日
next_n_month_end_day = get_end_day_of_month(next_n_month_first_day.year, next_n_month_first_day.month)
# 指定日と月末日比較
if day > next_n_month_end_day.day:
# 指定日>月末日の場合、月末日をリターン
return next_n_month_end_day
else:
# 指定日をリターン
return date(next_n_month_end_day.year, next_n_month_end_day.month, day)
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。