Home > Back-end >  Filtering json using date parameters in ISO format (having "Z" value)
Filtering json using date parameters in ISO format (having "Z" value)

Time:11-19

I have a json file which looks like this: { "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", }

In above json, I want to iterate through each json node using python. If created_at date > input_date1 (e.g.2022-11-10) and create_at date < input_date2 (e.g. 2022-11-13), include the node into a new json file. In above case, the new json file should only contain the second and third nodes. I am new to python so having difficulty working with the date formats. Needed some help in doing this.

CodePudding user response:

I assume that the top level node in your json is a list. The following should work:

import json
import datetime

js = json.loads('[{ "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"}]'
  )

out = []
for key in js:
    dt = datetime.datetime.strptime(key['created_at'][:-1] '000', "%Y-%m-%dT%H:%M:%S.%f")
    if input_date1 < dt < input_date2:
        out.append(key)
      

js_out = json.dumps(out)
  • Related