Search code examples
pythonpandasdatetimenat

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

enter image description here

output with NaT:

enter image description here


Solution

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