[SOLVED] Sorting strings containing dates with Python


This Content is from Stack Overflow. Question asked by Ahleya Sheikh

I’ve got a bunch of strings in this format.

[24/4/2018 15:47:20] doctor's appt
[22/8/2016 11:47:09] workshop @ block 3
[24/4/2018 15:45:33] buy eggs
[31/2/2017 13:44:40] good day
[31/2/2017 13:44:35] flight

I’m trying to sort them in an ascending order according to the date and time using Python but I can’t really figure it out. I’d really appreciate some help.


Ignoring that 31/2/2017 is an invalid date, this should do it for you:

from datetime import datetime

lst = []
file = open('dates.txt', 'r')
for line in file.readlines():
    formatStr = '[%d/%m/%Y %H:%M:%S]'
    datePart = ' '.join(line.split(' ')[0:2])
    dateobj = datetime.strptime(datePart, formatStr).date()
    lst.append((dateobj, line))


This assumes all of your dates are in a file called dates.txt one per line in the format you specified.

This Question was asked in StackOverflow by Ahleya Sheikh and Answered by Michael M. It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?