简体   繁体   中英

Python -Is there a way to sort a list of strings which contain a date and time within

Say this is my list of values:

my_list = ['Version1 2016,03,12 22:30', 'Version2 2016,03,29 23:00', 'Version3 2016,04,07 16:00', 'Version4 2016,02,24 15:00']

Is there a way to sort the list by the earliest date and time but by keeping the the Version at the front of the string.

You'd have to parse the datetime substring when sorting:

from datetime import datetime

sorted(my_list, key=lambda x: datetime.strptime(x.split(maxsplit=1)[1], '%Y,%m,%d %H:%M'))

['Version4 2016,02,24 15:00',
 'Version1 2016,03,12 22:30',
 'Version2 2016,03,29 23:00',
 'Version3 2016,04,07 16:00']

You can use sorted with a custom key:

list(sorted(my_list, key=lambda x: x.split(" ", maxsplit=1)[1])
['Version4 2016,02,24 15:00',
 'Version1 2016,03,12 22:30',
 'Version2 2016,03,29 23:00',
 'Version3 2016,04,07 16:00']

If the date is in the format you give, you do not need to parse it as a datetime, lexicographical order is enough

You can use sorted with a custom key:

list(sorted(my, key=lambda x: x.split(" ", maxsplit=1)[1]))
import re
from datetime import datetime

sorted(my_list, key=lambda x: datetime.strptime(re.sub(r"Version.", "", x).strip(), "%Y,%m,%d %H:%M"))

Output:

['Version4 2016,02,24 15:00',
 'Version1 2016,03,12 22:30',
 'Version2 2016,03,29 23:00',
 'Version3 2016,04,07 16:00']

THis could work as well:

print sorted(l, key=lambda x: int("".join([i for i in x if i.isdigit()])))

using pandas

import pandas as pd
data = ['Version1 2016,03,12 22:30', 'Version2 2016,03,29 23:00', 'Version3 2016,04,07 16:00', 'Version4 2016,02,24 15:00']
df = pd.DataFrame(data)
df = pd.concat([df, df[0].str.split(" ", n=1, expand=True)], axis=1)
df.columns = ["text","version","timestamp"]
df.timestamp = pd.to_datetime(df.timestamp, format="%Y,%m,%d %H:%M")
df.sort_values("timestamp")["text"].tolist()    

output

['Version4 2016,02,24 15:00',
 'Version1 2016,03,12 22:30',
 'Version2 2016,03,29 23:00',
 'Version3 2016,04,07 16:00']

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