Python生成两个日期之间的日期列表 [英] Python generating a list of dates between two dates
本文介绍了Python生成两个日期之间的日期列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想生成两个日期之间的日期列表,并将它们存储在字符串格式的列表中。此列表可用于与我的其他日期进行比较。
I want to generate a list of dates between two dates and store them in a list in string format. This list is useful to compare with other dates I have.
我的代码如下:
from datetime import date, timedelta
sdate = date(2019,3,22) # start date
edate = date(2019,4,9) # end date
def dates_bwn_twodates(start_date, end_date):
for n in range(int ((end_date - start_date).days)):
yield start_date + timedelta(n)
print(dates_bwn_twodates(sdate,edate))
我现在的输出:
<generator object dates_bwn_twodates at 0x000002A8E7929410>
我的预期输出:
['2019-03-22',.....,'2019-04-08']
我的代码有问题。
推荐答案
您可以使用 pd.date_range()
为此:
You can use pd.date_range()
for this:
pd.date_range(sdate,edate-timedelta(days=1),freq='d')
DatetimeIndex(['2019-03-22', '2019-03-23', '2019-03-24', '2019-03-25',
'2019-03-26', '2019-03-27', '2019-03-28', '2019-03-29',
'2019-03-30', '2019-03-31', '2019-04-01', '2019-04-02',
'2019-04-03', '2019-04-04', '2019-04-05', '2019-04-06',
'2019-04-07', '2019-04-08'],
dtype='datetime64[ns]', freq='D')
这篇关于Python生成两个日期之间的日期列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文