我需要在python中获取给定日期之间的季度列表。
例如: start_date = 2012年3月, end_date = 2013年6月
预期产出:
['March 2012', 'June 2012', 'September 2012', 'December 2012', 'March 2013', 'June 2013']
我检查了其他线程,例如generate time series by quarter, increment by one quarter,但我的要求略有不同。我需要它与上面提到的完全相同的格式。
答案 0 :(得分:2)
使用date_range
添加一个quarter
,上次更改格式为strftime
:
r = (pd.date_range(pd.to_datetime(start_date),
pd.to_datetime(end_date) + pd.offsets.QuarterBegin(1), freq='Q')
.strftime('%B %Y')
.tolist())
print (r)
['March 2012', 'June 2012', 'September 2012', 'December 2012', 'March 2013', 'June 2013']
答案 1 :(得分:1)
使用datetime
和dateutil
<强>演示:强>
import datetime
from dateutil.relativedelta import relativedelta
def getQ(start_date, end_date):
res = [start_date]
start_date = datetime.datetime.strptime(start_date, "%B %Y")
end_date = datetime.datetime.strptime(end_date, "%B %Y")
while True:
cDate = start_date + relativedelta(months=3)
if cDate >= end_date:
break
res.append(cDate.strftime("%B %Y"))
start_date = cDate
return res
start_date = 'March 2012'
end_date = 'June 2013'
print(getQ(start_date, end_date))
<强>输出:强>
['March 2012', 'June 2012', 'September 2012', 'December 2012', 'March 2013']
答案 2 :(得分:1)
这是一个强大的:
from datetime import datetime
from dateutil import relativedelta
start_date, end_date = 'March 2012', 'June 2013'
start_date, end_date = datetime.strptime(start_date, '%B %Y'), datetime.strptime(end_date, '%B %Y')
delta = relativedelta.relativedelta(end_date, start_date)
result = [datetime.strftime(start_date + relativedelta.relativedelta(months=i), '%B %Y')\
for i in range(0, delta.years * 12 + delta.months + 1, 3)]
result
#['March 2012',
# 'June 2012',
# 'September 2012',
# 'December 2012',
# 'March 2013',
# 'June 2013']
但它有效。