Karthikeyan
Karthikeyan

Reputation: 21

Pandas datetime: can't convert object in dd-mm-YYYY format to datetime in correct format

I have a pandas dataframe

Sl.No   Date1
1   08-09-1990
2   01-06-1988
3   04-10-1989
4   15-11-1991
5   01-06-1968

The dtype of Date1 is object

When i tried to convert this object to datetime format.

df["Date1"]= pd.to_datetime(df["Date1"])

I am getting the output as

0   1990-08-09
1   1988-01-06
2   1989-04-10
3   1991-11-15
4   2068-01-06

Also I tried with:

df["Date1"]= pd.to_datetime(df["Date1"],format='%d-%m-%Y')

and

df["Date1"]= pd.to_datetime(df["Date1"],format='%d-%m-%Y', dayfirst = True)

Problem is :

  1. in index 0 the month and day is interchanged

  2. in index 4 the year is taken incorrectly as 2068 instead of 1968

Upvotes: 1

Views: 953

Answers (1)

BENY
BENY

Reputation: 323376

Pass the dayfirst to to_datetime

pd.to_datetime(df.Date1,dayfirst=True)
0   1990-09-08
1   1988-06-01
2   1989-10-04
3   1991-11-15
4   1968-06-01
Name: Date1, dtype: datetime64[ns]

Upvotes: 1

Related Questions