Reputation: 63
I have a Dataframe:
TRADE_DATE TICKET_TIME GATE_ENTRY_TIME GATE_EXIT_TIME
2016-09-23 18:00:27 18:02:28 18:55:35
2016-09-23 18:08:48 18:09:01 18:31:11
2016-09-23 19:05:33 19:06:33 19:41:43
2016-09-23 18:06:55 18:08:42 18:34:41
2016-09-23 10:31:35 10:32:06 10:47:27
I want to create a new column by extracting the hours from the datetime.time values in column TICKET_TIME.
I have tried df['HOUR'] = df['TICKET_TIME'].dt.hour, but it didn't work:
AttributeError: Can only use .dt accessor with datetimelike values
Upvotes: 3
Views: 2332
Reputation: 862641
Use list comprehension if working with time
s:
print (type(df.loc[0,"TICKET_TIME"]))
<class 'datetime.time'>
df['Hour'] = [x.hour for x in df['TICKET_TIME']]
Alternative solution:
df['Hour'] = pd.to_datetime(df['TICKET_TIME'].astype(str)).dt.hour
print (df)
TRADE_DATE TICKET_TIME GATE_ENTRY_TIME GATE_EXIT_TIME Hour
0 2016-09-23 18:00:27 18:02:28 18:55:35 18
1 2016-09-23 18:08:48 18:09:01 18:31:11 18
2 2016-09-23 19:05:33 19:06:33 19:41:43 19
3 2016-09-23 18:06:55 18:08:42 18:34:41 18
4 2016-09-23 10:31:35 10:32:06 10:47:27 10
Upvotes: 8