Home > database >  get record from list of dictionary with latest date python
get record from list of dictionary with latest date python

Time:08-02

I have a dict like this

[{'name': 'name1' , 'date':'1997-07-16 19:20:00 01:00'},{'name': 'name3' , 'date':'2006-07-16 19:20:00 01:00'},{'name': 'name2' , 'date':'1992-07-16 19:20:00 01:00'}]

so want to get the latest one record from this list of object on basis of latest date and time . any help would be highly appreciated .

CodePudding user response:

You can use max with key= parameter:

data = [
    {"name": "name1", "date": "1997-07-16 19:20:00 01:00"},
    {"name": "name3", "date": "2006-07-16 19:20:00 01:00"},
    {"name": "name2", "date": "1992-07-16 19:20:00 01:00"},
]

latest = max(data, key=lambda k: k["date"])  # or min() for the opposite. Works only if all your timezones are  01:00. If not use strptime

print(latest)

Prints:

{'name': 'name3', 'date': '2006-07-16 19:20:00 01:00'}

EDIT: To sort data:

from datetime import datetime

data = [
    {"name": "name1", "date": "1997-07-16 19:20:00 01:00"},
    {"name": "name3", "date": "2006-07-16 19:20:00 01:00"},
    {"name": "name2", "date": "1992-07-16 19:20:00 01:00"},
]

data = sorted(
    data, key=lambda k: datetime.strptime(k["date"], "%Y-%m-%d %H:%M:%S%z")  # or reversed with reverse=True parameter
)
print(data)

Prints:

[
    {"name": "name2", "date": "1992-07-16 19:20:00 01:00"},
    {"name": "name1", "date": "1997-07-16 19:20:00 01:00"},
    {"name": "name3", "date": "2006-07-16 19:20:00 01:00"},
]
  • Related