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

获取日期列表中的连续日期,且表示成*年*月*日~*年*月*日

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

获取日期列表中的连续日期,且表示成*年*月*日~*年*月*日

#coding:utf-8
#作者    :思
#创建时间:2021/12/16 14:36 
#功能    :获取日期列表中的连续日期,且表示成*年*月*日~*年*月*日
import numpy as np
from itertools import groupby
import datetime
dlist = ['2021-03-01', '2021-04-01', '2021-06-06', '2021-06-25', '2021-06-26',
       '2021-06-27', '2021-07-28', '2021-08-29','2021-08-30','2021-08-31','2021-09-01']

def calculate_consecutive_dates(dlist):
    dates = [datetime.datetime.strptime(i, "%Y-%m-%d").date() for i in dlist]
    date_ints = [d.toordinal() for d in dates]
    print(date_ints)

    reslist = []
    fun = lambda x: x[1]-x[0]
    for k, g in groupby(enumerate(date_ints), fun):
        l1 = [j for i, j in g ]    # 连续数字的列表

        if len(l1)>2:#时间连续的点超过2天
            conl_start = datetime.date.fromordinal(l1[0])
            conl_end = datetime.date.fromordinal(l1[-1])
            conl_start = conl_start.strftime("%Y-%m-%d")
            conl_end = conl_end.strftime("%Y-%m-%d")
            conl_str = conl_start+'~'+conl_end
            print(conl_start,conl_end)
            print(conl_str)
            reslist.append(conl_str)
        else:
            for i in l1:
                i = datetime.date.fromordinal(i)
                i = i.strftime("%Y-%m-%d")
            reslist.append(i)
    print(reslist)
    # print(','.join(reslist))
    # ['2021-03-01', '2021-04-01', '2021-06-06', '2021-06-25~2021-06-27', '2021-07-28', '2021-08-29~2021-09-01']


if __name__ == '__main__':
    calculate_consecutive_dates(dlist)
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/674613.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

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

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