Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Sorting strings containing dates with Python

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading