Home > front end >  Find a value in JSON using Python by date
Find a value in JSON using Python by date

Time:11-18

I want to get the latest entry in a JSON. The JSON is not sorted in any way but there are dates associated to the other values.

My Json looks like this:

[
  {
    'bytes': 2853922,
    'date': '2021-11-08 12:03',
    'name': 'dummy1.mp4',
    'size': '2.7MB',
    'url': '/downloads/timelapse/dummy1.mp4'
  },
  {
    'bytes': 1402663,
    'date': '2021-11-18 11:57',
    'name': 'dummy2.mp4',
    'size': '1.3MB',
    'url': '/downloads/timelapse/dummy2.mp4'
  },
  {
    'bytes': 1318887,
    'date': '2021-11-11 11:28',
    'name': 'dummy3.mp4',
    'size': '1.3MB',
    'url': '/downloads/timelapse/dummy3.mp4'
  }
]

In this case I would want to get the values from dummy2.mp4.

How do I iterate through the JSON in order to get the latest date entry?

CodePudding user response:

Use max with a key function that parses the date:

import datetime

def date_from_entry(entry):
    return datetime.datetime.strptime(entry['date'], '%Y-%m-%d %H:%M')


latest = max(data, key=date_from_entry)['url']

print(latest)

Result:

/downloads/timelapse/dummy2.mp4

CodePudding user response:

I propose using date time

from datetime import datetime

maxdate = datetime.min
indx = None
for i,e in enumerate(parsed_json):
    date = datetime.strptime(e['date'], "%Y-%m-%d %H:%M")
    if date >  maxdate:
        indx = i
        maxdate = date
# now indx is set to the most recent date 
  • Related