user7491773
user7491773

Reputation:

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.

Upvotes: 2

Views: 87

Answers (6)

Rob Raymond
Rob Raymond

Reputation: 31166

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']

Upvotes: 0

cisman ali
cisman ali

Reputation: 1

THis could work as well:

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

Upvotes: 0

bigbounty
bigbounty

Reputation: 17368

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']

Upvotes: 0

FlorianGD
FlorianGD

Reputation: 2436

You can use sorted with a custom key:

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

Upvotes: 0

FlorianGD
FlorianGD

Reputation: 2436

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

Upvotes: 1

yatu
yatu

Reputation: 88236

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']

Upvotes: 3

Related Questions