Minh-Long Luu
Minh-Long Luu

Reputation: 2731

Python Pandas: convert DD.MM.YYYY to datetime

I have a DataFrame that looks like this:

date       | ...
09.01.2000 |
02.03.2001 | ...

The format is DD.MM.YYYY. I want to select only data where it is year 2014 (for example). I convert them into datetime using pd.to_datetime:

date = pd.to_datetime(table["date"], format = "%d.%m.%Y")

Then I want my table to take 3 new columns Day, Month, Year. I do:

table[["day", "month", "year"]] = date.dt.day, date.dt.month, date.dt.year

But it throws error: Must have equal len keys and value when setting with an ndarray How do I convert them into datetime properly to use df.loc[df["year"] == 2014]?

Upvotes: 1

Views: 468

Answers (1)

Quang Hoang
Quang Hoang

Reputation: 150735

You need to do manually:

table['day'], table['month'], table['year'] = date.dt.day, date.dt.month, date.dt.year

Explanation: date.dt.day, date.dt.month, date.dt.year is short hand for a tuple with length 3, which is most likely different from len(table).

On the other hand, since you already have date, you can also slice with:

table[date.dt.year==2014]

Upvotes: 3

Related Questions