Given a list of UNIX time stamp values:
l = ['1260633600', '1256993100', '1273255200', '1253450700']
I need the list to be sorted.
from datetime import datetime def humanize_unixtime(unix_time): time = datetime.fromtimestamp(int(unix_time)).strftime('%d-%m-%Y %H.%M') return time lsorted = sorted(l, key=lambda x: humanize_unixtime(x), reverse=True) print [humanize_unixtime(i) for i in lsorted]
When I run this, I got ['31-10-2009 13.45', '20-09-2009 14.45', '12-12-2009 17.00', '07-05-2010 20.00']
, which is not at all sorted. Can you see what’s wrong?
Advertisement
Answer
You’re sorting by the humanized output (the string), not by the times. Notice that the first value starts with '3'
, the second with '2'
and the third with '1'
which is exactly what you expect when you sort strings with reverse=True
.
change your key=lambda ...
to key=int
and all should work.