编程语言
首页 > 编程语言> > python获取上月、当月、下月的开始和结束日期

python获取上月、当月、下月的开始和结束日期

作者:互联网

获取上月开始结束日期

方法一

import datetime
import calendar


def get_date_of_last_month():
    """
    获取上月开始结束日期
    :return: str,date tuple
    """
    today = datetime.date.today()
    today = datetime.date(2022, 1, 1)
    year = today.year
    month = today.month
    if month == 1:
        year -= 1
        month = 12
    else:
        month -= 1

    begin_of_last_month = datetime.date(year, month, 1).strftime('%Y-%m-%d')
    _, day = calendar.monthrange(year, month)
    end_of_last_month = datetime.date(year, month, day).strftime('%Y-%m-%d')
    return begin_of_last_month, end_of_last_month

方法二

import datetime


def get_date_of_last_month():
    """
    获取上月开始结束日期
    :return: str,date tuple
    """
    today = datetime.date.today()
    year = today.year
    month = today.month
    if month == 1:
        begin_of_last_month = datetime.date(year - 1, 12, 1).strftime('%Y-%m-%d')
    else:
        begin_of_last_month = datetime.date(year, month - 1, 1).strftime('%Y-%m-%d')
    end_of_last_month = (datetime.date(year, month, 1) + datetime.timedelta(-1)).strftime('%Y-%m-%d')
    return begin_of_last_month, end_of_last_month

获取当月开始结束日期

import datetime
import calendar


def get_date_of_month():
    """
    获取当月开始结束日期
    :return: str,date tuple
    """
    today = datetime.date.today()
    year = today.year
    month = today.month
    begin_of_month = datetime.date(year, month, 1).strftime('%Y-%m-%d')
    _, day = calendar.monthrange(year, month)
    end_of_month = datetime.date(year, month, day).strftime('%Y-%m-%d')
    return begin_of_month, end_of_month

获取下月开始结束日期

import datetime  
import calendar  
  
  
def get_date_of_next_month():  
    """  
    获取下月开始结束日期  
    :return: str,date tuple  
    """
    today = datetime.date.today()  
    year = today.year  
    month = today.month  
    if month == 12:  
        year += 1  
        month = 1  
    else:  
        month += 1  
  
    begin_of_next_month = datetime.date(year, month, 1).strftime('%Y-%m-%d')  
    _, day = calendar.monthrange(year, month)  
    end_of_next_month = datetime.date(year, month, day).strftime('%Y-%m-%d')  
    return begin_of_next_month, end_of_next_month

标签:-%,python,month,日期,当月,year,date,datetime,today
来源: https://www.cnblogs.com/rong-z/p/16281492.html