栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

使用Python统计连续日期

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

使用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]

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/619132.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号