python日期计算(限28天内)

@TOC

以前写的存一个,难得找。

   def date_count(self, date, deltaDay):
        '''
        该函数实现日期的增减,粗暴法,直接给多少差值计算多少差值,暂时只支持最多28天加减
        :param date: 当前日期
        :param delta: 差值日期
        :return:
        算法:分闰年,分日期
        '''
        datelist = date.split('-')
        year = datelist[0]
        month = datelist[1]
        day = datelist[2]
        int_year = self.str2int(year)
        int_month = self.str2int(month)
        int_day = self.str2int(day)

        this_month_day_count = self.getMonthDayCount(int_year, int_month)  # 获取本月日期数

        last_month = self.getLastMonth(int_month)  # 获取上一个月份
        next_month = self.getNextMonth(int_month)  # 获取下一个月份

        result_day = int_day + deltaDay  # 计算后的日数
        if result_day > this_month_day_count:  # 跨下月  当该数大于本月最大日期后,转到下一月,假如是6月28,加7天,28+7=35,35-30=5,就是7月5,注意跨年
            if int_month > next_month:  # 当本月大于下月时,说明本月是12月,跨年
                next_int_year = int_year + 1

                new_day = result_day - this_month_day_count
                # newDate = str(next_int_year) +'-'+self.int2str(next_month)+'-'+self.int2str(new_day)
                newDate = str(next_int_year) + '-01-' + self.int2str(new_day)
                return newDate

            else:  # 不跨年

                new_day = result_day - this_month_day_count
                newDate = year + '-' + self.int2str(next_month) + '-' + self.int2str(new_day)
                return newDate

        elif result_day < 1:  # 跳上月 当本来就是月初时,这会跳到上一月,假如是6月02,减7天,2-7=-5,上月31天,31-5=26,就是5月26
            if last_month > int_month:  # 当上月大于本月时,说明本月是1月上月12  ,跨年
                last_int_year = int_year - 1
                new_day = 31 + result_day
                newDate = str(last_int_year) + '-12-' + self.int2str(new_day)
                # print('跨年,上一月')
                return newDate

            else:
                last_month_endDay = self.getLastMonthDay(int_year, int_month)
                new_day = last_month_endDay + result_day
                newDate = year + '-' + self.int2str(last_month) + '-' + self.int2str(new_day)
                # print('不跨年,上一月')
                return newDate
        else:  # 本月
            newDate = year + '-' + month + '-' + self.int2str(result_day)
            return newDate

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值