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

如何筛选指定分钟内JSON数据?datetime模块时间对比疑问

筛选最近3分钟内的JSON数据及时间对比方案

我有大量JSON格式的数据,需要筛选出最近3分钟内的数据,跳过其余数据。同时有两个疑问:

  1. 怎么用datetime模块把小时转换成分钟来做时间对比?
  2. 处理时分值的比较,应该用datetime模块还是直接做字符串对比?

示例数据

data = [{'EventTime': '08/18/2022 08:06:52', 'Password_change': 'Success'},
        {'EventTime': '08/18/2022 08:05:10', 'Password_Change': 'Success'},
        {'EventTime': '08/18/2022 08:04:23', 'Password_Change': 'Success'},
        {'EventTime': '08/18/2022 05:06:52', 'Password_Change': 'Success'}]

初始代码

data = [{'EventTime': '08/18/2022 08:06:52', 'Password_change': 'Success'},
        {'EventTime': '08/18/2022 08:04:10', 'Password_Change': 'Success'},
        {'EventTime': '08/18/2022 08:03:23', 'Password_Change': 'Success'},
        {'EventTime': '08/18/2022 05:06:52', 'Password_Change': 'Success'}]
for i in data:
    split_time = i['EventTime'].split(' ')[1]
    time_detail = split_time
    print(time_detail)

优先用datetime模块,别用字符串对比

字符串对比看似简单,但坑点太多:

  • 只能处理同一天内的时间,跨天直接失效
  • 没法直接计算时间差,要自己拆分字符串转数值计算,容易出错
  • 时间格式稍有变化(比如少个前导零),逻辑直接崩溃

datetime模块是专门处理时间的工具,能直接解析时间字符串、计算时间差,逻辑清晰且不易出错。

完整实现代码

from datetime import datetime, timedelta

data = [{'EventTime': '08/18/2022 08:06:52', 'Password_change': 'Success'},
        {'EventTime': '08/18/2022 08:04:10', 'Password_Change': 'Success'},
        {'EventTime': '08/18/2022 08:03:23', 'Password_Change': 'Success'},
        {'EventTime': '08/18/2022 05:06:52', 'Password_Change': 'Success'}]

# 以数据中最晚时间为基准(实时场景可替换为datetime.now())
event_times = [datetime.strptime(item['EventTime'], '%m/%d/%Y %H:%M:%S') for item in data]
latest_time = max(event_times)
# 计算3分钟前的时间阈值
threshold_time = latest_time - timedelta(minutes=3)

# 筛选符合条件的数据
filtered_data = []
for item in data:
    event_time = datetime.strptime(item['EventTime'], '%m/%d/%Y %H:%M:%S')
    if event_time >= threshold_time:
        filtered_data.append(item)

print("筛选出的最近3分钟数据:")
for item in filtered_data:
    print(item)

关键步骤说明

  1. 解析时间字符串:用datetime.strptime()将字符串转成datetime对象,格式%m/%d/%Y %H:%M:%S对应你的时间格式(月/日/年 时:分:秒)
  2. 计算时间阈值:用最晚时间减去timedelta(minutes=3)得到3分钟前的时间点;实时场景直接用datetime.now()作为基准时间
  3. 时间对比:直接通过datetime对象的大小比较,判断事件时间是否在阈值范围内

关于「把小时转成分钟对比」的问题,其实不需要单独转换——datetime模块可以直接计算时间差并转成分钟数:

time_diff = latest_time - event_time
# 把时间差转换成总分钟数
total_minutes = time_diff.total_seconds() / 60
if total_minutes <= 3:
    # 数据符合条件

这样会自动把小时、分钟、秒统一转换成分钟数,无需手动拆分计算。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 02:45:36