pyC*_*hon 7 python datetime pandas
在尝试使用Python生成一系列半年度日期.Pandas
提供了一个pd.date_range
帮助这个的功能,但我希望我的日期范围从结束日期开始并向后迭代.
例如,给定输入:
start = datetime.datetime(2016 ,2, 8)
end = datetime.datetime(2018 , 6, 1)
pd.date_range(start, end, freq='6m')
Run Code Online (Sandbox Code Playgroud)
结果是:
DatetimeIndex(['2016-02-29', '2016-08-31', '2017-02-28', '2017-08-31',
'2018-02-28'])
Run Code Online (Sandbox Code Playgroud)
如何生成以下内容:
DatetimeIndex(['2016-02-08', '2016-06-01', '2016-12-01', '2017-06-01',
'2017-12-01', '2018-06-01'])
Run Code Online (Sandbox Code Playgroud)
使用更新的输出(来自您所做的编辑),您可以执行如下操作:
from pandas.tseries.offsets import DateOffset
end = datetime.datetime(2018 , 6, 1)
start = datetime.datetime(2016 ,2, 8)
#Get the range of months to cover
months = (end.year - start.year)*12 + end.month - start.month
#The frequency of periods
period = 6 # in months
pd.DatetimeIndex([end - DateOffset(months=e) for e in range(0, months, period)][::-1]).insert(0, start)
Run Code Online (Sandbox Code Playgroud)
这是一个相当简洁的解决方案,尽管我没有比较运行时间,所以我不确定它有多快。
基本上,这只是将您需要的日期创建为列表,然后将其转换为日期时间索引。