how to filter data from url using python on the basis of current date

Viewed 391

my question is how to extract data on two conditions,

  1. todays date,
  2. Minimum age limit should be 45 and above

can someone help me to sort this: how to filter the data from given JSON text?

I got the output from the code now I want to find out the center where the availability is there for above 45 age limit and above for today's date. I need to show the whole data of that center


    url = 'myurl'
    response = urllib.request.urlopen(url)
    data = json.loads(response.read())
    json_formatted_str = json.dumps(data, indent=2, )

output:


    {
      "centers": [
        {
          "center_id": 55,
          "name": "abc Hospital GH",
          "sessions": [
            {
              "session_id": "1a",
              "date": "06-05-2021",
              "available_capacity": 0,
              "min_age_limit": 45,
           
              "slots": [
                "09:00AM-11:00AM",
                "11:00AM-01:00PM",
                "01:00PM-03:00PM",
                "03:00PM-06:00PM"
              ]
            },
            {
              "session_id": "2a",
              "date": "07-05-2021",
              "available_capacity": 0,
              "min_age_limit": 45,
            }
          ]
        },
        {
          "center_id": 638690,
          "name": "xyz Hospital",
          "sessions": [
            {
              "session_id": "2a",
              "date": "06-05-2021",
              "available_capacity": 0,
              "min_age_limit": 45,
            }
          ]
        },
    ]
    }

4 Answers

The accepted answer will also return sessions that dont satisfy your criteria.

Here's a way to omit the sessions that dont match.

def center_check(center):
    center['sessions'] = [sess for sess in center['sessions'] if session_check(sess)]
    if center['sessions']:
        return True
    return False

def session_check(session):
    from datetime import date
    today = date.today().strftime("%d-%m-%Y")
    if session['date'] == today and session['min_age_limit'] >= 45:
        return True
    return False

[cent for cent in data['centers'] if center_check(cent)]

for compairing the data as per your need you need to exctract date and minimum age limit . for minimum age limit:

minimun_age_limit = json_formatted_str["centers"][1]["min_age_limit"]

and for date:

today = date.today()
d1 = today.strftime("%d-%m-%Y")
date_from_response = json_formatted_str["centers"][1]["date"]

if date_from_response.startswith(d1) and minimum_age_limit > 45:
   do your stuff here

Loop through the hospital dict:

from datetime import date
today = date.today().strftime("%d-%m-%Y")
out_lst = []
for x in a['centers']:
    for session in x['sessions']:
        if session['date'] == today and session['min_age_limit'] == 45:
            out_lst.append(x)
            print(x['center_id']); break
print(out_lst)

Here out_lst will be a list of all hospital dictionaries matching the criteria.

EDIT if you only want the relevant session:

today = date.today().strftime("%d-%m-%Y")
out_lst = []
for x in a['centers']:
  for session in x['sessions']:
    if session['date'] == today and session['min_age_limit'] == 45:
      out_lst.append(session)
      print(x['center_id']); break
print(out_lst)

Another solution using filter():

import json
from datetime import date
...
def condition(hospital):
    today = date.today().strftime("%d-%m-%Y")
    for session in hospital["sessions"]:
        if (session["date"] == today) and (session["min_age_limit"] >= 45):
            return True
    return False


filtered = filter(condition, data["centers"])
print(json.dumps(list(filtered)))

Edit:

If you want to omit other sessions you can upgrade the condition method as follows:

def condition(hospital):
    today = date.today().strftime("%d-%m-%Y")
    is_actual = False
    to_delete = []
    for session in hospital["sessions"]:
        if (session["date"] == today) and (session["min_age_limit"] >= 45):
            is_actual = True
        else:
            to_delete.append(session)
            
    for session in to_delete:
        hospital["sessions"].remove(session)
            
    return is_actual

This can be a little bit confusing, because the filter method is actually editing the object.

Related