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
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')
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')
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.