user6437539
user6437539

Reputation: 11

Extract date only from pandas' datetime.datetime column

I am using pandas to read an excel file which contains date and time data. I decided to leave the conversion to defaults (no converts used). The date column was converted to datetime.datatime (e.g. 1970-08-31 00:00:00). i wanted to extract the date part w/o time. I used df['Date']=df['Date'].date() which did not work even though when i tried the same on individual entries of the date column it worked (e.g. df['Date'][1].date(). Any help is greatly appreciated.

EK

Upvotes: 0

Views: 3161

Answers (1)

Tom McLean
Tom McLean

Reputation: 6295

Use the following:

df['Date'] = df['Date'].dt.date

To get the dates of a datetime series.

When you do df["Date"][0].date you are accessing the first item in df["Date"], which is an datetime-like object which has the property .date. When you do df["Date"].date you are trying to access the date property of a pandas series, which has no property .date. By using df["Date"].dt.date, it is first returning the Accessor object for datetimelike properties of the Series values, dt, of which you can apply .date to.

https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.dt.html

Upvotes: 3

Related Questions