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

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

获取日期列表中的连续日期,且表示成*年*月*日~*年*月*日
#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)

欢迎分享,转载请注明来源:内存溢出

原文地址: https://www.outofmemory.cn/zaji/5679820.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-17
下一篇 2022-12-17

发表评论

登录后才能评论

评论列表(0条)

保存