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
Python/Pandas: How do I convert from datetime64[ns] to datetime
提问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 pandas
for 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 apply
function 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 datetime
module.
确保导入datetime
模块。
apply()
will take each cell at a time for evaluation and apply the formatting as specified in the lambda
function.
apply()
将一次获取每个单元格进行评估并应用lambda
函数中指定的格式。