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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39207640/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 01:54:42  来源:igfitidea点击:

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

python-2.7datetimepandasdatetime64

提问by mattrweaver

I have a script that processes an Excel file. The department that sends it has a system that generated it, and my script stopped working.

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

I suddenly got the error Can only use .str accessor with string values, which use np.object_ dtype in pandasfor the following line of code:

我突然收到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\._/-]', '')

I checked the type of the date columns in the file from the old system (dtype: object) vs the file from the new system (dtype: datetime64[ns]).

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

How do I change the date format to something my script will understand?

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

I saw this answerbut my knowledge about date formats isn't this granular.

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

回答by Varun Pius Rodrigues

You can use applyfunction on the dataframe column to convert the necessary column to String. For example:

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

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

Make sure to import datetimemodule.

确保导入datetime模块。

apply()will take each cell at a time for evaluation and apply the formatting as specified in the lambdafunction.

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

回答by Amandeep Singh

You can use pd.to_datetime

您可以使用pd.to_datetime

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