Jan-06-2021, 11:26 AM
(Jan-05-2021, 05:56 PM)WiPi Wrote: Hi guys,
I have a pandas generated dataframe (df) where the first column has a series of dates as below:
I need to change these dates to a format YY,MM,DD H:M
Output:0 11.26.2020 03:36 1 12.01.2020 15:00 2 12.01.2020 21:30 3 12.02.2020 13:26 4 12.04.2020 22:43 5 12.21.2020 00:05
If I look at the raw values in the df array:
df.values[:,0]We need to change these values to a DateTimeIndexArray and then parse to the correct string format:
Output:array(['11.26.2020 03:36', '12.01.2020 15:00', '12.01.2020 21:30', '12.02.2020 13:26', '12.04.2020 22:43', '12.21.2020 00:05'], dtype=object)
dti = pd.to_datetime(df.values[:,0]) dti = dti.strftime('%Y.%m.%d %H:%M') dti.values
This code gives this output:
So it looks like it's done what I want!
Output:array(['2020.11.26 03:36', '2020.12.01 15:00', '2020.12.01 21:30', '2020.12.02 13:26', '2020.12.04 22:43', '2020.12.21 00:05'], dtype=object)
Copying back the re-formatted dates to the df:
df.values[:,0] = dti.valuesThis does not work! The dates remain in the original format.
Any ideas please?
Just for completion and if it's any use to anyone I did figure this out. I just directly updated the column rather than using a dummy variable (dti). Column name is 'Open Date' and the code is below which works.
No idea why the original code stopped working as it had been fine up until now! The main issue was reassigning the new values back to the original.
df['Open Date']=pd.to_datetime(df.values[:,0]) #convert the 'date' column to DateTimeIndex array df['Open Date']= df['Open Date'].dt.strftime('%Y.%m.%d %H:%M') #parse to string and set date format