pythonsortingdatetimebazaar

How can I sort a date and time from oldest to newest in the format of ['2020-05-27 15:26:57', '2020-05-22 16:40:58']?


From a bzr repository I can return timestamps from different revision commits by using

branch.repository.get_revision(revision_id).timestamp

after I get the timestamp I can use: datetime.fromtimestamp(timestamp).strftime('%Y-%m-%d %H:%M:%S') to get the format of 2020-05-27 15:26:57.

I am going to store a number of these into a list and then from there I will need to sort them from the oldest date and time to the newest date and time. I looked at a bunch of the other questions already on here but none of the answers seemed to translate to this situation very easily.


Solution

  • calling sorted() on your list should do the trick:

    lst = ['2020-05-27 15:26:57','2020-06-27 15:26:57','2020-03-27 15:26:57']
    sorted(lst)
    
    Output: ['2020-03-27 15:26:57', '2020-05-27 15:26:57', '2020-06-27 15:26:57']
    

    We can also use lst.sort() to do the trick in the following way:

    lst.sort()
    lst
    Output: ['2020-03-27 15:26:57', '2020-05-27 15:26:57', '2020-06-27 15:26:57']