nutship
nutship

Reputation: 4924

Sorting a list of unix time stamp values

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?

Upvotes: 0

Views: 5015

Answers (3)

Vinodh
Vinodh

Reputation: 1

Convert string type to int in lambda function as the unix epoch time follows incremental order.

from datetime import datetime
l = ['1260633600', '1256993100', '1273255200', '1253450700']
def humanize_unixtime(unix_time):
    time = datetime.fromtimestamp(int(unix_time)).strftime('%d-%m-%Y %H.%M')
    return time

lsorted = sorted(l,key=lambda s: int(s), reverse=True)
print lsorted
print [humanize_unixtime(i) for i in lsorted]

Upvotes: 0

Ashif Abdulrahman
Ashif Abdulrahman

Reputation: 2147

Use this

from datetime import datetime
l = ['1260633600', '1256993100', '1273255200', '1253450700']
def humanize_unixtime(unix_time):
    time = datetime.fromtimestamp(int(unix_time)).strftime('%d-%m-%Y %H.%M')
    return time

lsorted = sorted(l, reverse=True)
print lsorted
print [humanize_unixtime(i) for i in lsorted]

here using lsorted = sorted(l, reverse=True) instead of

lsorted = sorted(l, key=lambda x: humanize_unixtime(x), reverse=True)

the you will get the output as

['07-05-2010 23.30', '12-12-2009 21.30', '31-10-2009 18.15', '20-09-2009 18.15']

which is perfectly sorted

Upvotes: 0

mgilson
mgilson

Reputation: 310019

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.

Upvotes: 3

Related Questions