2

I have a pandas dataframe with column with dates (datetime64[ns] format) The dates are listed as yyyy-mm-dd (like 2018-09-12). I want to convert it to dd-mm-yyyy but what i try doesn't seem to works:

pd.to_datetime(df['date'], format='%d-%m-%Y')
0    2018-09-12
1    2018-09-12

Edit: add example df

df.head(3)
        date      nr
0   2018-09-12   144
1   2018-09-12    37
2   2018-09-12    28

df.info()
date   datetime64[ns]
nr     int

The 'date' doesn't contain any Nan's or Nat's

jpp
  • 159,742
  • 34
  • 281
  • 339
J-man
  • 261
  • 1
  • 3
  • 10
  • 3
    Unfortunately, the example is not complete, so we cannot test it. However, the `format` parameter for `to_datetime` is used to specify the format used for parsing, not the one used for printing the parsed datetime instance. – languitar Sep 12 '18 at 09:13
  • Can you explain what you need to complete the example? Do I need to add a example of the dataframe? – J-man Sep 12 '18 at 09:17
  • No one know what your original `df` look like or `df['date']`. We can just guess. – languitar Sep 12 '18 at 09:17

2 Answers2

5

The dates are listed as yyyy-mm-dd (like 2018-09-12).

Yes, but this is not how they are stored. What you are seeing is a specific string representation of datetime objects. Internally, datetime values are stored as integers.

I want to convert it to dd-mm-yyyy but what i try doesn't seem to works

Correct, because pd.to_datetime converts to a datetime object. You need to instead convert your series to a series of strings, which will have object dtype:

df['date'] = df['date'].dt.strftime('%d-%m-%Y')
jpp
  • 159,742
  • 34
  • 281
  • 339
2

You need to convert the date parsed with to_datetime to a string in the desired representation. The display format you see right now is the default one used for Datetime objects:

In [10]: frame = {'date': ['2018-09-12', '2016-10-02']}

In [11]: pd.to_datetime(frame['date']).strftime('%d-%m-%Y')
Out[11]: Index(['12-09-2018', '02-10-2016'], dtype='object')
languitar
  • 6,554
  • 2
  • 37
  • 62