python - 如何从两个间隔中获取分割月份?

标签 python python-3.x

我有两个 YYYYmm 格式的日期

start : 202307
end : 202612

想要根据提供的间隔按间隔分割它们

例如 split_months ('202307,'202405',5),会给我

((202307,202311), (202312,202404), (202405,202405))

尝试使用以下代码,机器人陷入逻辑

def split_months(start, end, intv):
    from datetime import datetime
    periodList = []
    periodRangeSplitList = []

    start = datetime.strptime(start ,"%Y%m")
    end = datetime.strptime(end ,"%Y%m")
    mthDiff = relativedelta.relativedelta(end, start)

    if mthDiff == 0:
        periodRangeSplitList.append((start,start))
        return periodRangeSplitList

    diff = mthDiff / intv
    print(diff)

    for i in range(intv):
        periodList.append ((start + diff * i).strftime("%Y%m"))
    periodList.append(end.strftime("%Y%m"))
    print(periodList)

我尝试了上面的代码,但不起作用,有人可以分享任何建议吗?

谢谢

最佳答案

使用简单的 while 循环怎么样?

def split_months(start, end, intv):
    from datetime import datetime
    from dateutil import relativedelta
    
    periodList = []

    start = datetime.strptime(start, '%Y%m')
    end = datetime.strptime(end, '%Y%m')
    step = relativedelta.relativedelta(months=intv-1)

    start_ = start
    while (end_:=start_+step) <= end:
        # add new period
        periodList.append((start_, end_))
        # update next start
        start_ = end_ + relativedelta.relativedelta(months=1)
    
    # convert output to string 
    return [(s.strftime('%Y%m'), e.strftime('%Y%m'))
            for s, e in periodList]

split_months('202307', '202612', 5)

输出:

[('202307', '202311'),
 ('202312', '202404'),
 ('202405', '202409'),
 ('202410', '202502'),
 ('202503', '202507'),
 ('202508', '202512'),
 ('202601', '202605'),
 ('202606', '202610')]

如果要将最后一个间隔添加到末尾,请更改 while 条件并添加额外的行 (periodList.append((start_, end)) ):

def split_months(start, end, intv):
    from datetime import datetime
    from dateutil import relativedelta
    
    periodList = []

    start = datetime.strptime(start, '%Y%m')
    end = datetime.strptime(end ,'%Y%m')
    step=relativedelta.relativedelta(months=intv-1)

    start_ = start
    while (end_:=start_+step) < end:
        periodList.append((start_, end_))
        start_ = end_ + relativedelta.relativedelta(months=1)
    periodList.append((start_, end))
    
    return [(s.strftime('%Y%m'), e.strftime('%Y%m'))
            for s,e in periodList]

示例:

# split_months('202307', '202612', 5)
[('202307', '202311'),
 ('202312', '202404'),
 ('202405', '202409'),
 ('202410', '202502'),
 ('202503', '202507'),
 ('202508', '202512'),
 ('202601', '202605'),
 ('202606', '202610'),
 ('202611', '202612')]

# split_months('202307', '202610', 5)
[('202307', '202311'),
 ('202312', '202404'),
 ('202405', '202409'),
 ('202410', '202502'),
 ('202503', '202507'),
 ('202508', '202512'),
 ('202601', '202605'),
 ('202606', '202610')]

# split_months('202307','202405',5)
[('202307', '202311'),
 ('202312', '202404'),
 ('202405', '202405')]

关于python - 如何从两个间隔中获取分割月份?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/77086913/

相关文章:

python - 任何人都可以识别这种编码吗?

python - 在 BeautifulSoup 中打印和格式化结果

python - <function __main__.add_numbers(x, y)> 中的 __main__

python - Tkinter after() 函数显示异常行为

python - 在 python 3.7 中检索具有零长度匹配的 re.sub() 的 python 3.6 处理

django - 如何对两个单独的字段使用相同的 django_filters.CharFilter 字段

python - 如何在 Django 表单选择字段中设置默认值?

python - 正则表达式 Python 在单个表达式中提取两个字符串之间的数字

python - 有没有办法同时使用 .splitlines() 和 .split() ?

python - 在不知道路径的情况下使用 python 查找图像列表(可能是 .jpg)。