7

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?

6
  • 1
    In your case, with this date format (implying yyyy/mm/dd) as simple list.sort() would do the task. Commented Sep 10, 2019 at 15:03
  • What did you try? Commented Sep 10, 2019 at 15:03
  • 1
    I also checked out the sort function and the datetime library but couldnt get it to work Show us what you tried. If you just tell us you tried something, without showing the actual code, we can't point out what you did wrong. Commented Sep 10, 2019 at 15:04
  • For your sake don't override the builtin list. When you do that you can't use the list function anymore. Commented Sep 10, 2019 at 15:06
  • Thank you for your answer. When I run 'print list.sort()', it returns me 'None', am I doing it right? Commented Sep 10, 2019 at 15:07

3 Answers 3

13
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.

Sign up to request clarification or add additional context in comments.

Comments

4

Try this:

sorted_list = sorted( list )

=)

Comments

2

In this case, a simple list.sort() which sorts the list in place, or sorted(list) which returns a sorted copy of the list would work perfectly — as long as the dates and times follow Y/M/D H/M/S.

To get the first performed action in one line, you could use:

first_action = sorted(list)[0]

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.