1

I have the following 2D array, the date format is %Y-%m-%d %H:%M:%S :

[['second comment test', datetime.datetime(2018, 8, 22, 15, 49, 40), 's']
['this comment originated in service now', datetime.datetime(2018, 8, 22, 14, 45), 's']
['this is a longer description used for testing', datetime.datetime(2018, 8, 22, 14, 13, 49), 'z']]

I noticed that if one of the logs for time is at exactly a minute for example 2018-08-22 14:45:00 Meaning that it ends in 00 it wont log the seconds. So how can I order this array by date?

5
  • 1
    arr.sort(key=lambda x: x[1]) will sort by the second element in each list if your list is named arr. This will sort in-place. Commented Aug 22, 2018 at 15:57
  • What exactly is this? A numpy array or a Series? Or just a Python list? Commented Aug 22, 2018 at 15:57
  • datetime objects are stored internally as integers. Not sure why you think you have date format is %Y..... As such, sorting will work regardless of the seconds value being 0. Commented Aug 22, 2018 at 15:58
  • I agree with @jpp . You'll need a reproducible example for this Commented Aug 22, 2018 at 15:59
  • I am initializaing as this : all_comments = [] @DietrichEpp I just tried that and it says "'NoneType' object has no attribute 'sort'" Commented Aug 22, 2018 at 16:03

1 Answer 1

1

Assuming what you have is a list, as mentioned by @DietrichEpp, you can simply sort this array by:

list_ = [
    ['second comment test', datetime.datetime(2018, 8, 22, 15, 49, 40), 's'],
    ['this comment originated in service now', datetime.datetime(2018, 8, 22, 14, 45), 's'],
    ['this is a longer description used for testing', datetime.datetime(2018, 8, 22, 14, 13, 49), 'z'],]
list_.sort(key=lambda x: x[1])
Sign up to request clarification or add additional context in comments.

2 Comments

had to make some minor changes, but this is the correct answer. Thank you!
@MarioLanda, I'm glad to know it was useful.

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.