LiquidSnake
LiquidSnake

Reputation: 380

Sorting csv file with Python 3

I'm having trouble sorting a csv file which has in its second column the UTC time as: 2010-01-01 00:00:00

I have a file that is like this:

name        utc_time             longitude    latitude
A           2010-01-01 00:00:34  23           41
B           2011-01-01 10:00:00  26           44
C           2009-01-01 03:00:00  34           46
D           2012-01-01 00:00:00  31           47
E           2010-01-01 04:00:00  44           48
F           2013-01-01 14:00:00  24           41

Which I want it to be outputted in a csv file keeping the same structure but sorted by date:

Output:

name        utc_time             longitude    latitude
C           2009-01-01 03:00:00  34           46
A           2010-01-01 00:00:34  23           41
E           2010-01-01 04:00:00  44           48
B           2011-01-01 10:00:00  26           44
D           2012-01-01 00:00:00  31           47
F           2013-01-01 14:00:00  24           41

I'm actually trying this:

fileEru = pd.read_csv("input.csv")
fileEru = sorted(fileEru, key = lambda row: datetime.strptime(row[1],'%Y-%m-%d %H:%M:%S'), reverse=True)
fileEru.to_csv("output.csv")

But it doesn't work.

Upvotes: 3

Views: 501

Answers (1)

MaxU - stand with Ukraine
MaxU - stand with Ukraine

Reputation: 210882

try this:

(pd.read_csv("input.csv", parse_dates=['utc_time'])
   .sort_values('utc_time')
   .to_csv("output.csv", index=False))

Upvotes: 2

Related Questions