Home > OS >  Changing date order
Changing date order

Time:06-22

I have csv file containing a set of dates.

The format is like:

14/06/2000
15/08/2002
10/10/2009
09/09/2001
01/03/2003
11/12/2000
25/11/2002
23/09/2001

For some reason pandas.to_datetime() does not work on my data. So, I have split the column into 3 columns, as day, month and year. And now I am trying to combine the columns without "/" with:

df["period"] = df["y"].astype(str)   df["m"].astype(str)

But the problem is instead of getting:

 200006

I get:

  20006

One zero is missing. Could you please help me with that?

CodePudding user response:

This will allow you to take the column of dates and turn it into pd.to_datetime()

#This is assuming the column name is 0 as it was on my df 
#you can change that to whatever the column name is in your dataframe
df[0] = pd.to_datetime(df[0], infer_datetime_format=True)
df[0] = df[0].sort_values(ascending = False, ignore_index = True)
df

CodePudding user response:

The dayfirst= parameter might help you:

print(df)

            0
0  14/06/2000
1  15/08/2002
2  10/10/2009
3  09/09/2001
4  01/03/2003
5  11/12/2000
6  25/11/2002
7  23/09/2001

pd.to_datetime(df[0], dayfirst=True).sort_values()

0   2000-06-14
5   2000-12-11
3   2001-09-09
7   2001-09-23
1   2002-08-15
6   2002-11-25
4   2003-03-01
2   2009-10-10
  • Related