首页 > 编程语言 > 详细

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

时间:2020-10-16 12:03:47      阅读:42      评论:0      收藏:0      [点我收藏+]
代码实现,不论多少个月,都可以

    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

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

原文:https://blog.51cto.com/siweilai/2542036

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!