简体   繁体   English

Dataframe 列在转换为 pandas 日期时间格式时会导致 NaT

[英]Dataframe column when converting to pandas datetime format results in NaT

I read a csv file and try to convert my data frame column 'Date' to pandas.to_datetime format but it results in NaT.我读了一个 csv 文件并尝试将我的数据框列“日期”转换为 pandas.to_datetime 格式,但它会导致 NaT。 I need the date column should be converted to date format 'year-month-date'我需要将日期列转换为日期格式“年-月-日”

Code:代码:

df['Date'] = pd.to_datetime(df['Date'], errors='coerce', format= '%Y-%m-%d')

在此处输入图像描述

output with NaT: output 与 NaT:

在此处输入图像描述

Solved myself.自己解决了。 The format option requires the current format of the dataframe 'Date' column not the expected 'Date' format.格式选项需要 dataframe 'Date' 列的当前格式,而不是预期的 'Date' 格式。 I have given the expected format as format= '%Y-%m-%d' and changed to the current format of the date and it works.我已将预期格式指定为format= '%Y-%m-%d'并更改为日期的当前格式并且它可以工作。

Wrong code:错误代码:

df['Date'] = pd.to_datetime(df['Date'], errors='coerce', format= '%Y-%m-%d')

Right code:正确的代码:

df['Date'] = pd.to_datetime(df['Date'], errors='coerce', format= '%d-%m-%Y')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM