2016-02-16 76 views
6

在我试图使用Python生成一系列的半年度日期。 Pandas提供了一个函数pd.date_range来帮助这个,但是我希望我的日期范围从结束日期开始并向后迭代。熊猫date_range从结束日期开始日期

例如给定输入:

start = datetime.datetime(2016 ,2, 8) 
end = datetime.datetime(2018 , 6, 1) 
pd.date_range(start, end, freq='6m') 

结果是:

DatetimeIndex(['2016-02-29', '2016-08-31', '2017-02-28', '2017-08-31', 
       '2018-02-28']) 

我如何可以生成以下:

DatetimeIndex(['2016-02-08', '2016-06-01', '2016-12-01', '2017-06-01', 
       '2017-12-01', '2018-06-01']) 
+1

删除了我的初始答案。我认为这里主要的是抵消,是吗? – Maximilian

+0

@Maximilian是的,这是另一种说法。 – pyCthon

回答

4

有了更新的输出(从您所做的编辑),你可以这样做以下:

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) 

这是一个相当简洁的解决方案,尽管我没有比较运行时间,所以我不确定它有多快。

基本上这只是创建您需要作为列表的日期,然后将其转换为日期时间索引。

2

这可以不用熊猫并使用datutil来代替。然而,它更多地参与比它也许应该:

from datetime import date 
import math 
from dateutil.relativedelta import relativedelta 

#set up key dates 
start = date(2016 ,2, 8) 
end = date(2018 , 6, 1) 

#calculate date range and number of 6 month periods 
daterange = end-start 
periods = daterange.days *2//365 

#calculate next date in sequence and check for year roll-over 
next_date = date(start.year,math.ceil(start.month/6)*6,1) 
if next_date < start: next_date = date(next_date.year+1,next_date.month,1) 

#add the first two values to a list 
arr = [start.isoformat(),next_date.isoformat()] 

#calculate all subsequent dates using 'relativedelta' 
for i in range(periods): 
    next_date = next_date+ relativedelta(months=+6) 
    arr.append(next_date.isoformat()) 


#display results 
print(arr) 
+0

我在'next_date ='行发现'TypeError:expected expected,float float'错误。 – pyCthon

+0

@pyCthon next_date是哪一行?第一个还是for循环中的一个?如果是后者,那么它可能是你没有安装dateutil,我应该提到。 –

+0

第一个,dateutil已安装,我有''2.4.2'' – pyCthon

相关问题