Python中生成指定日期区间内季度列表的实现需求
Python Solution to Generate Quarterly List in Specified Date Range
Got it, let's tackle this problem head-on. Below is a Python implementation that generates the exact quarterly list format you need, matching your example perfectly.
First, we'll use datetime for core date handling and relativedelta (from the python-dateutil library) to easily add months without worrying about year rollovers. If you don't have python-dateutil installed, run pip install python-dateutil first to set it up.
The Code
from datetime import date from dateutil.relativedelta import relativedelta def generate_quarterly_list(start_year, start_month, end_year, end_month): # Convert input year/month to date objects (day set to 1 for simplicity) start_date = date(start_year, start_month, 1) end_date = date(end_year, end_month, 1) # Calculate the first quarter-end month (3, 6, 9, 12) that's >= the start month first_quarter_month = ((start_month + 2) // 3) * 3 current_quarter = date(start_year, first_quarter_month, 1) quarterly_list = [] while current_quarter <= end_date: # Format to "Month Year" (e.g., "March 2012") using full month name quarterly_str = current_quarter.strftime("%B %Y") quarterly_list.append(quarterly_str) # Jump to the next quarter by adding 3 months current_quarter += relativedelta(months=3) return quarterly_list # Test with your example input result = generate_quarterly_list(2012, 3, 2013, 6) print(result) # Output: ['March 2012', 'June 2012', 'September 2012', 'December 2012', 'March 2013', 'June 2013']
How It Works
Let's break down the key bits:
- Date Conversion: We turn your input year/month values into
dateobjects (using day=1 since we only care about the year and month). - First Quarter Calculation: The formula
((start_month + 2) // 3) * 3maps any month to its corresponding quarter-end month:- Months 1-3 → 3 (March)
- Months 4-6 → 6 (June)
- Months 7-9 → 9 (September)
- Months 10-12 → 12 (December)
- Loop Through Quarters: We start at the first valid quarter end, format it to your required string style, then add 3 months each iteration until we go past the end date.
- String Formatting:
strftime("%B %Y")gives us the full month name followed by the 4-digit year, exactly matching your desired output.
Edge Case Tests
- If start is Jan 2012 and end is Mar 2012: returns
['March 2012'] - If start is Oct 2012 and end is Jan 2013: returns
['December 2012'] - If start is Jul 2013 and end is Nov 2013: returns
['September 2013', 'December 2013']
内容的提问来源于stack exchange,提问作者yadav
相关产品推荐
相关产品推荐

