简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM