Python/Pandas: 如何从 datetime64[ns] 转换为 datetime

Python/Pandas: How do I convert from datetime64[ns] to datetime

我有一个处理 Excel 文件的脚本。发送它的部门有一个生成它的系统,我的脚本停止工作了。

我突然收到以下代码行的错误 Can only use .str accessor with string values, which use np.object_ dtype in pandas

df['DATE'] = df['Date'].str.replace(r'[^a-zA-Z0-9\._/-]', '')

我检查了旧系统文件 (dtype: object) 与新系统文件 (dtype: datetime64[ns]) 中日期列的类型。

如何将日期格式更改为我的脚本可以理解的格式?

我看到了 ,但我对日期格式的了解不是那么详细。

您可以在数据框列上使用 apply 函数将必要的列转换为字符串。例如:

df['DATE'] = df['Date'].apply(lambda x: x.strftime('%Y-%m-%d'))

确保导入 datetime 模块。

apply() 将一次对每个单元格进行评估,并应用 lambda 函数中指定的格式。

您可以使用pd.to_datetime

df['DATE'] = pd.to_datetime(df['DATE'])

pd.to_datetime returns 一系列 datetime64 dtype,如下所述:

https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.to_datetime.html

df['DATE'] = df['Date'].dt.date

或者这个:

df['Date'].map(datetime.datetime.date)