Sorting strings containing dates with Python

Question:

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.

Edit: Hi guys thanks a lot for taking out your time to help me out here. Was able to solve it, appreciate it.

Asked By: Ahleya Sheikh

||

Answers:

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))

print(lst)
print(sorted(lst))

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

Answered By: Michael M.
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.