运维开发网

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

运维开发网 https://www.qedev.com 2020-10-17 08:26 出处:51CTO 作者:siweilai
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

扫码领视频副本.gif

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号