码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2020-10-18 16:20:46      阅读:18      评论:0      收藏:0      [点我收藏+]

标签:date   day   info   get   latest   lse   ptime   elf   end   

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

    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实现提前几月的方法实现

标签:date   day   info   get   latest   lse   ptime   elf   end   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!