连续时间周期生成 (Python datetime 时间 加减法)

工作中经常需要用到连续的时间周期, Excel并不能特别好的生成(每次新建一个表也挺慢的)
于是本着磨刀不误砍柴工的精神, 写了一个脚本来自动生成.
生成的周期是格式如下, 如有其它需求自行修改代码吧~

DSgenerato

支持:
月周期(6位)
e.g. 201912,202001
天周期(8位)
e.g. 20191231,20200101
小时周期(10位)
e.g. 2019123122,2019123123,2020010100,2020010101
分钟周期(12位)
e.g. 201912312340,201912312350,202001010000,202001010010

from __future__ import print_function
import sys
import datetime


def generateDS(start_time, end_time, step):
    output=[]
    numds = len(start_time)
    if numds != len(end_time) or int(start_time) > int(end_time): raise Exception("Wrong Input DS!")
    step = int(step)

    #分钟级生成
    if numds == 12:
        while int(start_time) <= int(end_time):
            output.append(start_time)
            start_time = (datetime.datetime.strptime(start_time,"%Y%m%d%H%M")+datetime.timedelta(minutes=step)).strftime("%Y%m%d%H%M")

    #小时级别生成
    elif numds == 10:
        while int(start_time) <= int(end_time):
            output.append(start_time)
            start_time = (datetime.datetime.strptime(start_time,"%Y%m%d%H")+datetime.timedelta(hours=step)).strftime("%Y%m%d%H")

    #天级别生成
    elif numds == 8:
        while int(start_time) <= int(end_time):
            output.append(start_time)
            start_time = (datetime.datetime.strptime(start_time,"%Y%m%d")+datetime.timedelta(days=step)).strftime("%Y%m%d")

    #月级别
    elif numds == 6:
        from dateutil.relativedelta import relativedelta
        while int(start_time) <= int(end_time):
            output.append(start_time)
            start_time = (datetime.datetime.strptime(start_time,"%Y%m")+relativedelta(months=step)).strftime("%Y%m")

    return output

# 输入
argvs = "{query}".strip()

if ("," in argvs and " " not in argvs):
    start_time, end_time, step = argvs.split(",")
elif ", " in argvs:
    start_time, end_time, step = argvs.replace(" ","").split(",")
else:
    start_time, end_time, step = argvs.split(" ")

# 输出
print(",".join(generateDS(start_time, end_time, step)),end="")

当然Bob也将这个小脚本写进了上一篇的 Alfred workflow 里

注意! 要使用本workflow请先在您的Mac上安装好Alfred:
1. 点击直达 Alfred 下载页面.
2. 点击直达 Workflow 下载页面.