loading...

Sorting ISO 8601 timestamps

adnauseum profile image Samuel Kendrick ・2 min read

Let's suppose I have a list of timestamps:

timestamps = [
  '2020-06-02T16:47:50Z',
  '2020-05-08T01:25:10Z',
  '2020-05-08T19:51:29Z',
  '2020-06-04T20:23:02Z',
  '2020-05-27T02:23:14Z',
  '2020-05-12T16:32:08Z',
  '2020-05-06T01:58:21Z',
  '2020-05-14T16:11:31Z',
  '2020-05-08T14:25:36Z',
  '2020-05-22T20:48:13Z',
  '2020-05-10T02:43:44Z'
];

Maybe a more "real-world" example would be scenario where you have a list of dictionaries and you want to sort by their created_date attribute. How would you do it?

If we wanted to sort our timestamps we could parse the date string into a date object and then use some compare function to correctly sort the list.

Fortunately, there's a nicer solution! Some date formats, such as ISO 8601 can be sorted merely as strings.

How can this be?

The ISO 8601 format is lexicographically ordered. If you have an ordered set of names: "Carlton" and "Carlyle." When ordered, "Carlton" precedes "Carlyle" because the 5th letter "t" is less than "y".

If you have two timestamps: "2020-05-08T19:51:29Z" and "2020-05-08T01:25:10Z", they differ at the 12th character and, because of the leading 0, the first timestamp comes after the second timestamp.

This is all do say that you can sort your timestamps very easily:

timestamps = [
  '2020-06-02T16:47:50Z',
  '2020-05-08T01:25:10Z',
  '2020-05-08T19:51:29Z',
  '2020-06-04T20:23:02Z',
  '2020-05-27T02:23:14Z',
  '2020-05-12T16:32:08Z',
  '2020-05-06T01:58:21Z',
  '2020-05-14T16:11:31Z',
  '2020-05-08T14:25:36Z',
  '2020-05-22T20:48:13Z',
  '2020-05-10T02:43:44Z'
];
timestamps.sort() # Yay!

Discussion

markdown guide