0

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.

5
  • if they were in proper ISO format, you could just sort by string value Commented Sep 17, 2022 at 18:22
  • What's is the "bunch"? A list, a DataFrame, plain text in a file? Commented Sep 17, 2022 at 18:38
  • If they're in a list (or could be put in a list), sort() admits an optional parameter key that would allow to use a function to extract the dates and convert them to datetimes. But maybe a different solution could be more suitable for a dataframe. Commented Sep 17, 2022 at 18:43
  • FYI: 31/2/2017 is not a valid date. There is no 31st of February. Commented Sep 17, 2022 at 18:46
  • @Matiiss hiya thanks a lot for the help! that really simplified things! Commented Sep 17, 2022 at 18:53

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

thanks a lot! that makes so much sense. and yea they're in a txt file so you really gave me a perfect solution. appreciate it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.