Skip to main content
 首页 » 编程设计

python之获取时间间隔内的所有日期

2025年05月04日20davidwang456

给定两个日期,例如:

December 1, 2017 
June 1, 2018 

我想得到这个结果:

January 1, 2018 
February 1, 2018 
March 1, 2018 
April 1, 2018 
May 1, 2018 
June 1, 2018 

另外,我还想修改区间。在上述情况下,间隔是每月一次。我还希望它成为每季度和每半年一次。

因此,给定 2017 年 12 月 1 日 和 2018 年 6 月 1 日,它将生成 2018 年 3 月 1 日 半年等等在...

我也希望它包括在内,这意味着结束日期也应该包括在内

是否有用于此的 python 包或函数?

请您参考如下方法:

Pendulum — and specifically its 'range' function —对此有好处。

它将为您提供每月间隔日期和我认为的三个月间隔日期。

>>> import pendulum 
>>> start = pendulum.Pendulum(2017, 12, 1) 
>>> end = pendulum.Pendulum(2018, 6, 1) 
>>> period = pendulum.period(start, end) 
>>> [dt.format('%Y-%m-%d') for dt in  period.range('months')] 
['2017-12-01', '2018-01-01', '2018-02-01', '2018-03-01', '2018-04-01', '2018-05-01', '2018-06-01'] 
>>> [dt.format('%Y-%m-%d') for dt in  period.range('months', 3)] 
['2017-12-01', '2018-03-01', '2018-06-01']