简体   繁体   中英

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. 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:

在此处输入图像描述

Solved myself. The format option requires the current format of the dataframe 'Date' column not the expected 'Date' format. I have given the expected format as format= '%Y-%m-%d' and changed to the current format of the date and it works.

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')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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