前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >python 月初日・月末日・下月日期・翌月 取得

python 月初日・月末日・下月日期・翌月 取得

原创
作者头像
刀枪不入de王二花
发布2022-10-10 13:11:41
4150
发布2022-10-10 13:11:41
举报
文章被收录于专栏:BETTERBETTER

下边代码可直接拷贝使用

N月后,月初日取得

代码语言:javascript
复制
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

测试:

代码语言:javascript
复制
>>> 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)

月末日取得

代码语言:javascript
复制
# 指定年月の最終日を取得
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

指定月、指定日取得

代码语言:javascript
复制
# 指定月・指定日取得(例:翌月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 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • N月后,月初日取得
  • 月末日取得
  • 指定月、指定日取得
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档