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

如何用Python基于带Z的ISO格式日期过滤JSON数据

解决JSON数据按日期区间筛选的Python实现

第一步:修正原始JSON格式

你提供的原始JSON数据格式存在问题,多个独立对象未包裹在数组中,Python无法正常解析,需调整为如下格式:

[
    {
        "id": 618831,
        "project_id": 1670,
        "source": "schedule",
        "created_at": "2022-11-09T00:31:10.112Z",
        "updated_at": "2022-11-09T02:16:53.223Z"
    },
    {
        "id": 618833,
        "project_id": 1669,
        "source": "schedule",
        "created_at": "2022-11-11T00:31:10.600Z",
        "updated_at": "2022-11-11T02:16:53.740Z"
    },
    {
        "id": 618835,
        "project_id": 1671,
        "source": "schedule",
        "created_at": "2022-11-12T00:31:10.601Z",
        "updated_at": "2022-11-12T02:16:53.741Z"
    }
]

第二步:两种日期筛选方案

方案1:直接利用ISO日期字符串比较

created_at采用标准ISO 8601格式,这类字符串的字典序与时间顺序完全一致,可直接提取日期部分进行比较,简单高效:

import json

# 读取原始JSON文件(假设文件名为data.json)
with open('data.json', 'r', encoding='utf-8') as f:
    data = json.load(f)

# 定义筛选的日期区间
input_date1 = "2022-11-10"
input_date2 = "2022-11-13"

# 筛选符合条件的节点
filtered_data = []
for item in data:
    # 提取created_at中的日期部分
    created_date = item['created_at'].split('T')[0]
    if input_date1 < created_date < input_date2:
        filtered_data.append(item)

# 将结果写入新JSON文件
with open('filtered_data.json', 'w', encoding='utf-8') as f:
    json.dump(filtered_data, f, indent=4, ensure_ascii=False)

方案2:用datetime模块解析日期(更严谨)

如果需要处理精确时间、时区等复杂场景,可通过datetime模块解析日期字符串后再比较:

import json
from datetime import datetime

# 读取原始JSON数据
with open('data.json', 'r', encoding='utf-8') as f:
    data = json.load(f)

# 将输入日期转换为datetime对象
input_date1 = datetime.strptime("2022-11-10", "%Y-%m-%d")
input_date2 = datetime.strptime("2022-11-13", "%Y-%m-%d")

filtered_data = []
for item in data:
    # 解析created_at字符串为datetime对象
    created_at = datetime.strptime(item['created_at'], "%Y-%m-%dT%H:%M:%S.%fZ")
    # 仅比较日期部分
    created_date = created_at.date()
    if input_date1.date() < created_date < input_date2.date():
        filtered_data.append(item)

# 写入结果文件
with open('filtered_data.json', 'w', encoding='utf-8') as f:
    json.dump(filtered_data, f, indent=4, ensure_ascii=False)

说明

  • 方案1适合仅需比较日期部分的简单场景,代码易读易写;
  • 方案2更严谨,支持精确时间、时区扩展(如需处理时区可引入pytz库);
  • 运行代码后,filtered_data.json将保存符合条件的第二、第三个节点。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 23:51:16