Felix Dango
Felix Dango

Reputation: 7

Find a value in JSON using Python by date

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?

Upvotes: 0

Views: 360

Answers (3)

Wizard.Ritvik
Wizard.Ritvik

Reputation: 11660

Alternatively, I'd propose not using datetime at all.

For example, consider that this is a sample value for a date time field:

'2021-11-08 12:03'

Which, as indicated above, would translate to this format:

'%Y-%m-%d %H:%M'

Using string ASCII comparison should be enough here, technically, since the datetime appears to be in valid ISO format, where the largest measure of time (year) appears to be first, and the shortest one appears to be last (minute).

Therefore, given that each - separated value is padded with two characters at a minimum, the following alone should work to retrieve the latest date from a data object:

latest = max(data, key=lambda entry: entry['date'])['url']

Result:

/downloads/timelapse/dummy2.mp4

Upvotes: 0

hpchavaz
hpchavaz

Reputation: 1388

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 

Upvotes: 0

rdas
rdas

Reputation: 21285

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

Upvotes: 4

Related Questions