我正在尝试仅显示当前财年过去几个月的数据。
示例:我的财政年度从 2022 年 7 月到 2023 年 6 月开始。如果当前日期是 2023 年 4 月 10 日,那么我应该显示从 7 月到 3 月的数据。四月、五月、六月不应显示。
示例: 当前表格显示所有月份。
| 01 |七月 | 1 |
| 02 |八月 | 1 |
| 03 |九月 | 1 |
| 04 |十月 | 1 |
| 05 |十一月 | 1 |
| 06 |十二月 | 1 |
| 07|简 | 1 |
| 08 |二月 | 1 |
| 09|三月 | 1 |
| 10 | 10四月 | 1 |
| 11 | 11五月 | 1 |
| 12 | 12六月 | 1 |
数据应显示如下
当前日期:2023-04-01(当前月份为四月)
| 01 |七月 | 1 |
| 02 |八月 | 1 |
| 03 |九月 | 1 |
| 04 |十月 | 1 |
| 05 |十一月 | 1 |
| 06 |十二月 | 1 |
| 07|简 | 1 |
| 08 |二月 | 1 |
| 09|三月 | 1 |
您可以使用此脚本根据当前日期生成会计年度月份,并过滤掉不应显示的月份。
安装日历模块。
import calendar
from datetime import datetime, timedelta
def get_fiscal_year_months(current_date):
fiscal_year_start_month = 7 # Fiscal year starts in July
fiscal_year_end_month = 6 # Fiscal year ends in June
fiscal_year_start = datetime(current_date.year - 1, fiscal_year_start_month, 1)
fiscal_year_end = datetime(current_date.year, fiscal_year_end_month, calendar.monthrange(current_date.year, fiscal_year_end_month)[1])
if current_date < fiscal_year_start:
fiscal_year_start = datetime(current_date.year - 2, fiscal_year_start_month, 1)
fiscal_year_end = datetime(current_date.year - 1, fiscal_year_end_month, calendar.monthrange(current_date.year - 1, fiscal_year_end_month)[1])
fiscal_year_months = []
current_month = fiscal_year_start
while current_month <= fiscal_year_end:
fiscal_year_months.append(current_month)
current_month += timedelta(days=calendar.monthrange(current_month.year, current_month.month)[1])
return fiscal_year_months
def display_data_for_fiscal_year(data, fiscal_year_months):
filtered_data = [row for row in data if row["MonthDate"] in fiscal_year_months]
return filtered_data
# Example data
data = [
{"SORT": 1, "MonthName": "July", "FY2023": 1, "MonthDate": datetime(2022, 7, 1)},
{"SORT": 2, "MonthName": "Aug", "FY2023": 1, "MonthDate": datetime(2022, 8, 1)},
# ... (add other months)
{"SORT": 10, "MonthName": "Apr", "FY2023": 1, "MonthDate": datetime(2023, 4, 1)},
{"SORT": 11, "MonthName": "May", "FY2023": 1, "MonthDate": datetime(2023, 5, 1)},
{"SORT": 12, "MonthName": "June", "FY2023": 1, "MonthDate": datetime(2023, 6, 1)},
]
# Example: Current date is 2023-04-01
current_date = datetime(2023, 4, 1)
# Get fiscal year months
fiscal_year_months = get_fiscal_year_months(current_date)
# Display data for the fiscal year
filtered_data = display_data_for_fiscal_year(data, fiscal_year_months)
for row in filtered_data:
print(row)