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']?

1.6k Views Asked by At

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.

2

There are 2 best solutions below

6
ai.jennetta On BEST ANSWER

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']
2
Dorian On

Since the date and time are already sorted from most-influential to least influential, just use the build-in sort() method for the list.

list = [timestamp_1, timestamp_2, ...]
list.sort()  # now its sorted

This works since all your dates/times have the same format and so on.

To make it faster, you can also leave out the conversion to a string and just use the unix-timestamp for sorting. You can always later on convert is to a string with your method, to make it readable.