Home > Blockchain >  How to convert time format in pandas
How to convert time format in pandas

Time:11-15

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:

  • Related