你不應該需要使用不必要的循環或像熊貓這樣的大型庫來做到這一點。你可以用簡單的整數除法/算術和只有日期時間庫(儘管使用更清晰的代碼使用dateutil結果)。
import datetime
def getQuarterStart(dt=datetime.date.today()):
return datetime.date(dt.year, (dt.month - 1) // 3 * 3 + 1, 1)
# using just datetime
def getQuarterEnd1(dt=datetime.date.today()):
nextQtYr = dt.year + (1 if dt.month>9 else 0)
nextQtFirstMo = (dt.month - 1) // 3 * 3 + 4
nextQtFirstMo = 1 if nextQtFirstMo==13 else nextQtFirstMo
nextQtFirstDy = datetime.date(nextQtYr, nextQtFirstMo, 1)
return nextQtFirstDy - datetime.timedelta(days=1)
# using dateutil
from dateutil.relativedelta import relativedelta
def getQuarterEnd2(dt=datetime.date.today()):
quarterStart = getQuarterStart(dt)
return quarterStart + relativedelta(months=3, days=-1)
輸出:
>>> d1=datetime.date(2017,2,15)
>>> d2=datetime.date(2017,1,1)
>>> d3=datetime.date(2017,10,1)
>>> d4=datetime.date(2017,12,31)
>>>
>>> getQuarterStart(d1)
datetime.date(2017, 1, 1)
>>> getQuarterStart(d2)
datetime.date(2017, 1, 1)
>>> getQuarterStart(d3)
datetime.date(2017, 10, 1)
>>> getQuarterStart(d4)
datetime.date(2017, 10, 1)
>>> getQuarterEnd1(d1)
datetime.date(2017, 3, 31)
>>> getQuarterEnd1(d2)
datetime.date(2017, 3, 31)
>>> getQuarterEnd1(d3)
datetime.date(2017, 12, 31)
>>> getQuarterEnd1(d4)
datetime.date(2017, 12, 31)
>>> getQuarterEnd2(d1)
datetime.date(2017, 3, 31)
>>> getQuarterEnd2(d2)
datetime.date(2017, 3, 31)
>>> getQuarterEnd2(d3)
datetime.date(2017, 12, 31)
>>> getQuarterEnd2(d4)
datetime.date(2017, 12, 31)
爲什麼'relativedelta(月= 3) - dt.timedelta(天= 1)',而不是'relativedelta(月= 3天= -1)'? – Paul
@保羅 - 是的,那樣更好。謝謝。我將編輯帖子。 – Charon