如何将pd.to_timedelta()转换为time()对象?

时间:2017-04-21 05:39:12

标签: python pandas time timedelta

我需要0 days 08:00:0008:00:00

代码:

import pandas as pd 
df = pd.DataFrame({
'Slot_no':[1,2,3,4,5,6,7], 
'start_time':['0:01:00','8:01:00','10:01:00','12:01:00','14:01:00','18:01:00','20:01:00'], 
'end_time':['8:00:00','10:00:00','12:00:00','14:00:00','18:00:00','20:00:00','0:00:00'], 
'location_type':['not considered','Food','Parks & Outdoors','Food',
'Arts & Entertainment','Parks & Outdoors','Food']})

df = df.reindex_axis(['Slot_no','start_time','end_time','location_type','loc_set'], axis=1)

df['start_time'] = pd.to_timedelta(df['start_time']) 
df['end_time'] = pd.to_timedelta(df['end_time'].replace('0:00:00', '24:00:00'))

输出:

print (df)
   Slot_no  start_time        end_time         location_type  loc_set
0        1    00:01:00 0 days 08:00:00        not considered      NaN
1        2    08:01:00 0 days 10:00:00                  Food      NaN
2        3    10:01:00 0 days 12:00:00      Parks & Outdoors      NaN
3        4    12:01:00 0 days 14:00:00                  Food      NaN
4        5    14:01:00 0 days 18:00:00  Arts & Entertainment      NaN
5        6    18:01:00 0 days 20:00:00      Parks & Outdoors      NaN
6        7    20:01:00 1 days 00:00:00                  Food      NaN

1 个答案:

答案 0 :(得分:1)

您可以to_datetime使用dt.time

df['end_time_times'] = pd.to_datetime(df['end_time']).dt.time
print (df)
   Slot_no  start_time        end_time         location_type  loc_set  \
0        1    00:01:00 0 days 08:00:00        not considered      NaN   
1        2    08:01:00 0 days 10:00:00                  Food      NaN   
2        3    10:01:00 0 days 12:00:00      Parks & Outdoors      NaN   
3        4    12:01:00 0 days 14:00:00                  Food      NaN   
4        5    14:01:00 0 days 18:00:00  Arts & Entertainment      NaN   
5        6    18:01:00 0 days 20:00:00      Parks & Outdoors      NaN   
6        7    20:01:00 1 days 00:00:00                  Food      NaN   

  end_time_times  
0       08:00:00  
1       10:00:00  
2       12:00:00  
3       14:00:00  
4       18:00:00  
5       20:00:00  
6       00:00:00