如何在Python中创建仅包含完整天数的月份列表

1 投票
1 回答
47 浏览
提问于 2025-04-14 16:36

考虑以下的日期时间索引:

from calendar import monthrange
import pandas as pd

index_h = pd.date_range(start='2022-01-04 00:00:00', end='2023-01-10 23:00:00', freq='H')

我们可以看到2022年1月和2023年1月都是不完整的。

我该如何创建一个列表,里面包含这个范围内完整的月份和年份呢?

我尝试使用calendar里的monthrange来计算这些值,但不太确定接下来该怎么做:

years_months = index_h.to_period('M').unique()
complete_month_year_list = []
for year_month in years_months:
    num_days = monthrange(year_month.year, year_month.month)[1]
    if what_goes_here??? == num_days:    
        print(f"Month {year_month.month} of year {year_month.year} is complete.")
        complete_month_year_list.append(?????)
    else:
        print(f"Month {year_month.month} of year {year_month.year} is not complete.")

1 个回答

0

你可以通过检查一个月的天数是否等于这个月的总小时数来实现这个目标。如果两者相等,说明这个月已经结束了。

你还可以通过比较这个月的索引长度和这个月预期的小时数来进行判断。

from calendar import monthrange
import pandas as pd

index_h = pd.date_range(start='2022-01-04 00:00:00', end='2023-01-10 23:00:00', freq='H')

years_months = index_h.to_period('M').unique()
complete_month_year_list = []

for year_month in years_months:
    # Calculate the number of days in the month
    num_days = monthrange(year_month.year, year_month.month)[1]
    # Filter the index for the current month and year
    month_index = index_h[index_h.to_period('M') == year_month]
    # Check if the number of hours in the month is equal to the number of days in the month
    if len(month_index) == num_days * 24:
        print(f"Month {year_month.month} of year {year_month.year} is complete.")
        complete_month_year_list.append(year_month)
    else:
        print(f"Month {year_month.month} of year {year_month.year} is not complete.")

print("List of complete months:", complete_month_year_list)

撰写回答