I tried convert 2018-08-22 11:13:00 (datetime64[ns]) to only 20180822 (object).
I have this code:
df_ICF_news['date'] = df_ICF_news['date'].apply(lambda x: pd.to_datetime(str(x), format='%Y%m%d'))
but don`t work:
ValueError: time data '2022-10-28 11:09:00' does not match format '%Y%m%d' (match)
CodePudding user response:
Use to_datetime
directly on the Series and don't provide a format, then use dt.strftime
with your output format:
df_ICF_news['date'] = pd.to_datetime(df_ICF_news['date']).dt.strftime('%Y%m%d')
CodePudding user response:
Considering that the dataframe is df_ICF_news
and that the column date
is of datetime64[ns]
, one option would be to use a list comprehension with pandas.Series.dt.strftime
as follows
df_ICF_news["date"] = [x.strftime("%Y%m%d") for x in df_ICF_news["date"]]
[Out]:
date
0 20180822
date object
dtype: object
If OP wants to use pandas.Series.apply
, one can do the following
df_ICF_news["date"] = df_ICF_news["date"].apply(lambda x: x.strftime("%Y%m%d"))
Notes:
- There are strong opinions on using
.apply()
, so one might want to read this: When should I (not) want to use pandas apply() in my code?