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

mat*_*ver 5 datetime python-2.7 pandas datetime64

我有一个处理 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\._/-]', '')
Run Code Online (Sandbox Code Playgroud)

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

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

我看到了这个答案,但我对日期格式的了解并不是那么精细。

小智 8

pd.to_datetime返回一系列datetime64dtype,如下所述:

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

df['DATE'] = df['Date'].dt.date
Run Code Online (Sandbox Code Playgroud)

或这个:

df['Date'].map(datetime.datetime.date) 
Run Code Online (Sandbox Code Playgroud)


小智 5

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

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

确保导入datetime模块。

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


Ama*_*ngh 2

您可以使用pd.to_datetime

df['DATE'] = pd.to_datetime(df['DATE'])
Run Code Online (Sandbox Code Playgroud)

  • 我不知道为什么这个答案被接受,因为我相信它维护类型 datetime64[ns] (56认同)