I have a list of dictionaries and would like to get the earliest date value (and date only!) from the list. See example below:
{'taps': [{'duration': 0,
'datetime': '2022-06-05T09:35:56.131498'},
{'duratin': 518,
'datetime': '2022-06-05T09:35:56.649846',
{'duration': 500,
'datetime': '2022-06-06T09:35:57.150820'}]}
From the example above, I want to get 2022-06-05.
CodePudding user response:
You can do with dateutil.parser
import dateutil.parser
date_list = sorted([dateutil.parser.isoparse(item['datetime']) for item in d['taps']])
print(date_list[0].strftime("%Y-%m-%d")) # Convert back to string
'2022-06-05'
Conver the into string format datetime to datetime format. Since it's in ISO standard you can use dateutil.parser
and sort the list and take the first element.
CodePudding user response:
In your example, datetimes are strings only, so this will print the earliest date: (working if strings are all in the format : YYYY-MM-DD...
)
items = {
'taps': [{
'duration': 0,
'datetime': '2022-06-05T09:35:56.131498'
}, {
'duratin': 518,
'datetime': '2022-06-05T09:35:56.649846'
}, {
'duration': 500,
'datetime': '2022-06-06T09:35:57.150820'
}]
}
min(items['taps'],key=lambda x:x['datetime'])['datetime'][:10] # 2022-06-05
If you are working with datetime
objects, use this:
items = {
'taps': [{
'duration': 0,
'datetime': datetime(2022, 6, 5, 9, 35, 56, 131498)
}, {
'duratin': 518,
'datetime': datetime(2022, 6, 5, 9, 35, 56, 649846)
}, {
'duration': 500,
'datetime': datetime(2022, 6, 6, 9, 35, 57, 150820)
}]
}
min(items['taps'], key=lambda x: x['datetime'])['datetime'].strftime('%Y-%m-%d') # 2022-06-05