Reputation: 77
I have a list of dictionaries (from a JSON) containing date and time strings
[{"time": "17:00", "foo": "bar", "date": "01.02.20"}, {"time": "17:00", "foo": "bar", "date": "15.01.20"}, ...
The dates have the following format: %d.%m.%y, the times: %H:%M
my current code:
def sortJSON(self, lis, dateKey, timeKey):
if timeKey:
return sorted(lis, key = lambda i: (i[dateKey], i[timeKey]))
return sorted(lis, key = lambda i: i[dateKey])
However, since the dates are strings and of format %d.%m.%y they are not sorted correctly. Is there an elegant way of combining my current code with something like this:
In other words, passing in an additional function to handle the values as dates?
Upvotes: 0
Views: 114
Reputation: 21
def sortIt(key):
from datetime import datetime
thelist = [{"date": '30.10.2020'},
{"date": '30.01.2020'},
{"date": '30.06.2020'},
{"date": '17.01.2012'},
{"date": '25.04.2020'},
{"date": '03.02.2016'}]
# Unsorted
print("-------Unsorted------")
print(thelist)
print("-------Sorted------")
x = sorted(thelist, key = lambda i : datetime.strptime(i.get(key), "%d.%m.%Y"))
print(x)
sortIt('date')
Upvotes: 0
Reputation: 106455
You can convert the dates to datetime.datetime
objects for comparisons:
from datetime import datetime
def sortJSON(self, lis, dateKey, timeKey):
return sorted(lis, key=lambda i: (datetime.strptime(i[dateKey], '%d.%m.%y'), i.get(timeKey)))
Upvotes: 2
Reputation: 4510
You were pretty close, you need to convert the string
dates into datetime
objects, so python
can compare those objects according to time, this will work:
from datetime import datetime
d = [{"time": "17:00", "foo": "bar", "date": "01.02.20"}, {"time": "17:00", "foo": "bar", "date": "15.01.20"}]
sorted_dates = sorted(d, key=lambda date: datetime.strptime(date['time'] + ' ' + date['date'], '%H:%M %d.%m.%y'))
print(sorted_dates)
>>> [{'time': '17:00', 'foo': 'bar', 'date': '15.01.20'}, {'time': '17:00', 'foo': 'bar', 'date': '01.02.20'}]
Upvotes: 2