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?
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.
Try this:
sorted_list = sorted( list )
=)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With