编程语言
首页 > 编程语言> > python3实现提前几月的方法实现

python3实现提前几月的方法实现

作者:互联网

代码实现,不论多少个月,都可以

    def _get_cal_date(self, months):
        """
        :param months: 提前月份
        :return: 提前月份信息
        """
        today = datetime.date.today().strftime("%Y-%m-%d")
        cur_year = int(str(today)[0:4])
        cur_month = int(str(today)[5:7])
        cur_day = str(today)[8:10]
        try:
            # 最近 months 月数
            if cur_month - months == 0:
                latest_year = cur_year - 1
                latest_month = 12
            elif cur_month - months < 0:
                year_int = months // 12
                months_re = months % 12
                if year_int in (0, 1):
                    latest_year = cur_year - 1
                else:
                    latest_year = cur_year - year_int
                if cur_month - months_re == 0:
                    latest_month = 12
                elif cur_month - months_re > 0:
                    latest_month = cur_month - months_re
                else:
                    latest_month = 12 - (months_re - cur_month)
            else:
                latest_year = cur_year
                latest_month = cur_month - months
            # latest_date = calendar.monthrange(year, month)
            day = str(latest_year) + '-' + str(latest_month) + '-' + cur_day
            day = datetime.datetime.strptime(day, "%Y-%m-%d")
        except Exception as e:
            _logger.info(f'_get_cal_date :{e}')
        return day

标签:cur,实现,几月,months,month,year,day,python3,latest
来源: https://blog.51cto.com/siweilai/2542036