Search code examples
pythondataframedatetime-format

Convert DataFrame column from string to datetime for format "January 1, 2001 Monday"


I am trying to convert a dataframe column "date" from string to datetime. I have this format: "January 1, 2001 Monday".

I tried to use the following:

from dateutil import parser
for index,v in df['date'].items():
   df['date'][index] = parser.parse(df['date'][index])  

But it gives me the following error:

ValueError: Cannot set non-string value '2001-01-01 00:00:00' into a StringArray.

I checked the datatype of the column "date" and it tells me string type.

This is the snippet of the dataframe:

enter image description here

Any help would be most appreciated!


Solution

  • why don't you try this instead of dateutils, pandas offer much simpler tools such as pd.to_datetime function:

    df['date'] = pd.to_datetime(df['date'], format='%B %d, %Y %A')