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

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

获取上月开始结束日期

方法

import datetimedef get_date_of_last_month():    """    获取上月开始结束日期    :return: str,date tuple    """    today = datetime.date.today()    days_count = datetime.timedelta(today.day)    end_date = today - days_count    year_month = end_date.strftime("%Y-%m")    begin_of_last_month = f"{year_month}-01"    end_of_last_month = end_date.strftime("%Y-%m-%d")    return begin_of_last_month, end_of_last_month

方法二

import datetimeimport calendardef 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 datetimedef 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 datetimeimport calendardef 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
免责声明:本网信息来自于互联网,目的在于传递更多信息,并不代表本网赞同其观点。其原创性以及文中陈述文字和内容未经本站证实,对本文以及其中全部或者部分内容、文字的真实性、完整性、及时性本站不作任何保证或承诺,并请自行核实相关内容。本站不承担此类作品侵权行为的直接责任及连带责任。如若本网有任何内容侵犯您的权益,请及时联系我们,本站将会在24小时内处理完毕。
相关文章
返回顶部