0

I am having difficulty with converting date object into datetime.

My date & time object within the df looks like this:

Date
2/28/20 18:00

and I am doing this to convert it to datetime format;

from datetime import datetime
df['Date'] = pd.to_datetime(df['Date'], format='%m/%d/%y %H:%M)

I thought this worked as when I do dtypes I am getting the Date column in datetime format. This is how the date column became reflected as after running the above:

Date
2020-02-28 18:00:00

However after converting to datetime, I would like to split the datetime column into 'Date' and 'Time', with the data displayed like this:

Date           Time
2020-02-28     18:00   

I tried to run this:

df['Date'] = df['Date'].dt.strftime('%Y-%m-%d')
df['Time'] = df['Date'].dt.strftime('%H:%M')

but am getting 'AttributeError: Can only use .dt accessor with datetimelike values'

The main goal I want to achieve after splitting the into 2 columns, date and time, is so that I can then remove duplicates and keep only the last timing for each date in the dataframe.

Any advice appreciated, thanks in advance.

1 Answers1

1

The problem is that in the next df['Date'].dt, df['Date'] has been converted to string. You need to swap the assign sequence.

df['Time'] = df['Date'].dt.strftime('%H:%M')
df['Date'] = df['Date'].dt.strftime('%Y-%m-%d')
Ynjxsjmh
  • 28,441
  • 6
  • 34
  • 52