waithira
waithira

Reputation: 340

How to extract Hour from object

How can I get another column with the hour only from a column whose data type is an object whose format is this 9/5/21 18:00 ?

I have tried converting it to datetime first but I can't seem to get it right

df['starttime'] =  pd.to_datetime(df['starttime'], format='%m-%d-%y %H:%M')

the error is

time data '9/5/21 18:00' does not match format '%m-%d-%y %H:%M' (match)

Upvotes: 0

Views: 216

Answers (1)

Corralien
Corralien

Reputation: 120391

You use - instead of / as a separator of the date part:

df = pd.DataFrame({'starttime': ['9/5/21 18:00']})
df['starttime'] = pd.to_datetime(df['starttime'], format='%m/%d/%y %H:%M')
df['hour'] = df['starttime'].dt.hour
df['time'] = df['starttime'].dt.time
print(df)

# Output
            starttime  hour      time
0 2021-09-05 18:00:00    18  18:00:00

Upvotes: 2

Related Questions