Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort a list by datetime in python?

I am writing a .py file to sort lists by time which contain the following information

date, time, emp_id, action_performed

There is a question asked about this on stackoverflow but I couldn't exactly follow(I am new to python)

I also checked out the sort function and the datetime library but couldnt get it to work.

list = 
[
('2017/09/10 13:19:38', 'employee_id', 'enrolled'),
('2017/09/10 12:15:21', 'employee_id', 'deleted'),
('2017/09/10 21:19:34', 'employee_id', 'enrolled'),
('2017/09/10 22:42:50', 'employee_id', 'deleted'),
('2017/09/10 16:53:03', 'employee_id', 'enrolled')
]

I just want to know which action was performed first. Can someone help me out?

like image 968
Ebenezer Isaac Avatar asked Jan 25 '23 20:01

Ebenezer Isaac


2 Answers

from datetime import datetime
list = 
[
('2017/09/10 13:19:38', 'employee_id', 'enrolled'),
('2017/09/10 12:15:21', 'employee_id', 'deleted'),
('2017/09/10 21:19:34', 'employee_id', 'enrolled'),
('2017/09/10 22:42:50', 'employee_id', 'deleted'),
('2017/09/10 16:53:03', 'employee_id', 'enrolled')
]
sorted_list = sorted(list, key=lambda t: datetime.strptime(t[0], '%Y/%m/%d %H:%M:%S'))

Use the key parameter of the sorted function, in this case it tells the function to parse the first element of each tuple as a datetime string with the format '%Y/%m/%d %H:%M:%S' and use that value for sorting.

like image 139
gmoshkin Avatar answered Jan 28 '23 11:01

gmoshkin


Try this:

sorted_list = sorted( list )

=)

like image 28
lenik Avatar answered Jan 28 '23 09:01

lenik