Search code examples
pythonpandasdatetimedataframestring-to-datetime

Convert Pandas Column to DateTime With Rare Date Format


I have one column on my dataframe that follows this date format:

17 MAY2016

I've tried to follow this reference: http://strftime.org/ and pandas.to_datetime reference: http://pandas.pydata.org/pandas-docs/version/0.20/generated/pandas.to_datetime.html

My code is as follows: df1 =df1.apply(pandas.to_datetime, errors='ignore', format='%d %b%Y')

I also tried: format='%d/%b%Y' format='%d /%b%Y' and still doesn't work. The date column type is still and object. Any ideas? Thanks in advance


Solution

  • You can use to_datetime only:

    df = pd.DataFrame({'date':['17 MAY2016']})
    
    df['date'] = pd.to_datetime(df['date'])
    print (df)
            date
    0 2016-05-17
    

    If want format parameter:

    df['date'] = pd.to_datetime(df['date'], format='%d %b%Y')
    print (df)
            date
    0 2016-05-17
    

    If some non date values add errors='coerce' for convert them to NaT:

    df['date'] = pd.to_datetime(df['date'], errors='coerce')
    

    EDIT:

    For check use dtypes:

    print (df.dtypes)
    date    datetime64[ns]
    dtype: object