User 6683331
User 6683331

Reputation: 710

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

Upvotes: 1

Views: 5194

Answers (2)

James
James

Reputation: 36623

You don't need to use .apply, the to_datetime function natively works on pandas Series objects.

df1['date column'] = pd.to_datetime(df1['date column'], errors='ignore') 

Upvotes: 0

jezrael
jezrael

Reputation: 862761

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

Upvotes: 2

Related Questions