使用Python统计连续日期

输入为一串日期的长字符串,每个日期之间使用 "," 分隔开。

days_str = '''2021-11-17,2021-11-19,2021-11-20,2021-11-21,2021-11-23'''

统计连续出现日期的最大天数。        

    def calculate_consecutive_dates(dates_str: str):
        max_consecutive_days = 0
        temp_flag = 0
        dates_list = dates_str.split(",")
        dates = [datetime.strptime(d, "%Y-%m-%d") for d in dates_list]
        date_ints = [d.toordinal() for d in dates]

        retlist = list()
        count = 1
        # Avoid Index Error
        for i in range(len(date_ints) - 1):
            # Check if the next number is consecutive
            if date_ints[i] + 1 == date_ints[i + 1]:
                count += 1
            else:
                # If it is not append the count and restart counting
                retlist.append(count)
                count = 1
        # In case we stop the loop earlier then we should append the last count
        retlist.append(count)
        retlist.sort(reverse=True)
        return retlist[0]

关键函数:


        dates_list = dates_str.split(",") # 将字符串以某个分隔符分开,并返回一个list
        dates = [datetime.strptime(d, "%Y-%m-%d") for d in dates_list] # 将字符串以特定形式转换为日期型数据
        date_ints = [d.toordinal() for d in dates] # d.toordinal() 将日期转换为一个正整数。

        # 动态编程进行运算
        retlist = list()
        count = 1
        # Avoid Index Error
        for i in range(len(date_ints) - 1):
            # Check if the next number is consecutive
            if date_ints[i] + 1 == date_ints[i + 1]:
                count += 1
            else:
                # If it is not append the count and restart counting
                retlist.append(count)
                count = 1
        # In case we stop the loop earlier then we should append the last count
        retlist.append(count)
        retlist.sort(reverse=True)
        return retlist[0]

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值