0

So my issue is that I exported an excel file as a csv file. I've imported the file into Python and added it to a matrix which looks like:

A = [[1, '13/04/2015 12:22:45'],
     [2, '13/04/2015 12:22:46'],
     [3, '12/04/2015 12:30:00']]

I want to sort this by date and time. I have found several solutions that sort datetimes using the built in sorted() function, but none of the examples have additional array columns with other values.

Thanks for your help!

1
  • Could you share some code for your sorting for us to see what you have tried? Commented Apr 13, 2015 at 21:52

2 Answers 2

3

First, you probably want to be able to construct datetime objects from the strings that you have for comparison purposes:

import datetime
def make_datetime(lst):
    date_str = lst[1]
    return datetime.datetime.strptime(date_str, '%d/%m/%Y %H:%M:%s')

Now you can use this as the key to your sort function:

sorted_A = sorted(A, key=make_datetime)
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for your help! I didn't realise that I had to convert to a datetime object first. My original code was sorting based on the string like zachgates7's answer below. Thanks again!
0

You can sort by the second element (your datetime) using

A.sort(key=lambda i: i[1])

This is assuming that you want to sort by the string, rather than the actual date. Otherwise, take a look at mgilson's answer.

2 Comments

Hmmm... I think this doesn't quite work: [[1, '13/04/2015 00:00:00'], [2, '12/05/2015 00:00:00']] -- You can't compare as strings with the current date format OP is using.
I took back my upvote as, for example, "12/04/2000" > "11/05/2000" is True

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.