簡體   English   中英

Pandas date_range從結束日期開始到開始日期

[英]Pandas date_range starting from the end date to start date

在嘗試使用Python生成一系列半年度日期。 Pandas提供了一個函數pd.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'])

使用更新的輸出(來自您所做的編輯),您可以執行以下操作:

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)

這是一個相當簡潔的解決方案,雖然我沒有比較運行時,所以我不確定它有多快。

基本上這只是創建列表所需的日期,然后將其轉換為日期時間索引。

這可以在沒有pandas和使用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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM