Danish
Danish

Reputation: 2871

Extract only date from date time column pandas

I have data frame as shown below

Date_Time             
2019-02-27 10:00:00
2019-08-07 20:23:00
2019-02-24 00:00:00

from the above I would like to extract date only in new column as shown below.

Expected Output:

Date_Time               Date
2019-02-27 10:00:00     2019-02-27
2019-08-07 20:23:00     2019-08-07
2019-02-24 00:00:00     2019-02-24

Tried below code

df['Date']  = pd.to_datetime(df['Date_Time'], format="%m/%d/%Y").dt.floor('D')

But not providing required output

Upvotes: 4

Views: 13180

Answers (1)

Valdi_Bo
Valdi_Bo

Reputation: 30971

If you have Date_Time column as a string, start from converting it to datetime type:

df.Date_Time = pd.to_datetime(df.Date_Time)

Then run:

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

Other solution can be almost like yours, but with the format fitting the actual formatting of the source data (year-month-day):

pd.to_datetime(df['Date_Time'], format='%Y-%m-%d').dt.floor('D')

or even without format:

pd.to_datetime(df['Date_Time']).dt.floor('D')

Caution: Although both variants give the same printout, the actual results are different, what you can check running e.g. df.iloc[0,2].

  • In the first case the result is datetime.date(2019, 2, 27) (just date).
  • But in the second case the result is Timestamp('2019-02-27 00:00:00') (timestamp with "zeroed" time part).

Upvotes: 8

Related Questions