You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Pandas Datetime如何保留固定小时序列批量生成全年时间序列

实现方案

你可以直接生成全年小时级序列后过滤固定小时段,代码简洁高效:

import pandas as pd

# 配置时间范围和需要保留的小时
start_time = "2020-09-01 10:00:00"
end_time = "2021-09-01 14:00:00"
keep_hours = [10, 11, 12, 13, 14]

# 生成所有小时序列后过滤
all_hour = pd.date_range(start=start_time, end=end_time, freq="60min")
final_index = all_hour[all_hour.hour.isin(keep_hours)]

执行后final_index就是你需要的DatetimeIndex格式结果,完全符合预期的按天迭代10-14点的结构。

如果需要更高的自定义灵活性,也可以用按天生成再合并的写法:

import pandas as pd

# 生成全年日期(精确到天)
all_days = pd.date_range(start="2020-09-01", end="2021-09-01", freq="1D")
# 为每天拼接10-14点的时间点
final_index = pd.DatetimeIndex([
    day + pd.DateOffset(hour=h) 
    for day in all_days 
    for h in [10,11,12,13,14]
])

内容的提问来源于stack exchange,提问作者user6634965

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 05:24:04