0

Please consider below Dataset, enter image description here

The column with dates is 'Date Announced' ,current date format id 'DD-MM-YYYY' i want to change the date format to 'MM/DD/YYYY'. To do so i have written the following pandas code,

df3=pd.read_csv('raw_data_27th_APRonwards.csv',parse_dates=[0], dayfirst=True)
df3['Date Announced'] = pd.to_datetime(df3['Date Announced'])
df3['Date Announced'] = df3['Date Announced'].dt.strftime('%m/%d/%Y')

Post executing above code, i didn't get the desired output, please consider below Dataset, enter image description here

Notice in the output, Date '09/05/2020'is coming wrong , it should be like '05/09/2020' , there is a mix up btw date and month for this particular date. how to fix this?

  • in the first line of your code, you specify `parse_dates=[0], dayfirst=True` - so the column at index 0 should be parsed correctly. is that the case? I assume 'Date Announced' is at a different index; you might want to specify `dayfirst=True` here as well. – FObersteiner May 16 '20 at 14:35

1 Answers1

0

Do like this :

df3['Date Announced'] = pd.to_datetime(df3['Date Announced'], format='%d-%m-%Y')

Now :

df3['Date Announced'] = df3['Date Announced'].dt.strftime('%m/%d/%Y')

or pass parse_dates parameter while reading csv file like this:

pd.read_csv('your_file.csv', parse_dates=['Date Announced'])
Ehsan
  • 711
  • 2
  • 7
  • 21