如何在python datetime.time列中访问小时数

时间:2018-05-03 08:38:39

标签: python pandas dataframe

我有一个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

我想通过从TICKET_TIME列中的datetime.time值中提取小时来创建新列。

我试过df ['HOUR'] = df ['TICKET_TIME']。dt.hour,但它不起作用:

AttributeError: Can only use .dt accessor with datetimelike values

1 个答案:

答案 0 :(得分:4)

如果使用time s:

,请使用列表理解
print (type(df.loc[0,"TICKET_TIME"]))
<class 'datetime.time'>

df['Hour'] = [x.hour for x in df['TICKET_TIME']]

替代解决方案:

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