如何在Python中从DateTimeIndex提取完整天数的年月列表
找出DateTimeIndex中包含完整天数的年月列表
解决思路
判断一个月份是否完整,核心是对比该月份的总天数和索引中实际包含的该月份唯一日期数量(因索引是连续小时级数据,只要每一天有记录,就代表当天所有小时数据都存在)。
修改后的完整代码
from calendar import monthrange import pandas as pd # 生成小时级DateTimeIndex 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: # 获取该月份的总天数 num_days = monthrange(year_month.year, year_month.month)[1] # 筛选当前月份的索引,提取日期去重后统计实际天数 actual_days = index_h[index_h.to_period('M') == year_month].date.nunique() if actual_days == num_days: print(f"{year_month.year}年{year_month.month}月是完整月份。") # 可存储Period对象或转为字符串格式,示例用字符串 complete_month_year_list.append(str(year_month)) else: print(f"{year_month.year}年{year_month.month}月不是完整月份。") # 输出最终结果 print("\n完整月份列表:", complete_month_year_list)
代码说明
index_h.to_period('M') == year_month:筛选出当前年月对应的所有小时级索引.date.nunique():提取日期部分并去重,统计索引中实际覆盖的天数- 天数对比:若实际天数等于该月份总天数,说明该月份每一天都有完整小时数据,即为完整月份
内容的提问来源于stack exchange,提问作者Murilo
相关产品推荐
相关产品推荐

