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

Python实现按日期时间范围分组字典列表值的高效方法

问题:按日期时间范围分组字典列表中的值

我有一个如下的字典列表(精简版):

[{'2022-09-18 06:00:00': '5.4'}, {'2022-09-18 06:00:00': '6.0'}, {'2022-09-18 06:00:00': '6.5'}, {'2022-09-18 09:00:00': '6.9'}, {'2022-09-18 09:00:00': '7.9'}, {'2022-09-18 09:00:00': '8.5'},]

我希望将属于同一天且在特定时间范围(例如2022-09-18的06:00-12:00)内的值进行分组,期望输出如下:

[{'2022-09-18 06:00:00': (5.4, 6.0, 6.5, 6.9, 7.9, 8.5)}]  # Between 06:00-12:00

作为Python新手,我不确定是否有简便的实现方式,曾尝试编写如下自定义函数,但流程繁琐:

def separate_dates(dates_list):
    for i in range(len(dates)):
        time_int = dt.datetime.strptime(dates[i],"%Y-%m-%d %H:%M:%S")
        year = time_int.year
        month = time_int.month
        day = time_int.day
        hour = time_int.hour
    return time_int

请问是否存在更简便的实现方法?


简便实现方法

可以借助datetime模块处理时间判断,结合字典完成分组,代码更简洁直观:

from datetime import datetime

# 原始数据
data = [
    {'2022-09-18 06:00:00': '5.4'},
    {'2022-09-18 06:00:00': '6.0'},
    {'2022-09-18 06:00:00': '6.5'},
    {'2022-09-18 09:00:00': '6.9'},
    {'2022-09-18 09:00:00': '7.9'},
    {'2022-09-18 09:00:00': '8.5'},
]

# 定义目标日期和时间范围
target_date = datetime(2022, 9, 18).date()
start_hour = 6
end_hour = 12

# 初始化分组容器
grouped = {}
# 按需求用起始时间作为分组键
group_key = f"{target_date} 06:00:00"
grouped[group_key] = []

for item in data:
    # 快速取出单个字典的键值对(每个子字典仅一个键值)
    time_str, val_str = next(iter(item.items()))
    # 把字符串值转为浮点型
    value = float(val_str)
    # 转换为datetime对象方便判断
    dt_obj = datetime.strptime(time_str, "%Y-%m-%d %H:%M:%S")
    
    # 判断是否符合分组条件:日期匹配 + 小时在目标区间内
    if dt_obj.date() == target_date and start_hour <= dt_obj.hour < end_hour:
        grouped[group_key].append(value)

# 把列表转为元组,匹配期望输出格式
grouped[group_key] = tuple(grouped[group_key])
# 转成最终的列表格式
result = [grouped]
print(result)

代码说明

  • 直接用datetime定义目标日期和时间区间,逻辑清晰易修改
  • 用next(iter(item.items()))快速提取单个键值对,避免繁琐的循环取值
  • 时间判断借助date()方法匹配日期,hour属性判断区间,代码简洁
  • 如果需要支持多日期自动分组,只需把分组键改为日期字符串(比如dt_obj.date()),即可自动按日期归类

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 11:01:01