Converting Object to Time in python Pandas

I have a dataset that containes a column with “Time” values, but it’s showing as object, and I want to converte them to time so I can do a for loop to see if the time is between two times.

for i in df['Time']:
    if i >= dt.time(21,0,0) and i <= dt.time(7, 30,0) or i >= dt.time(3,0,0) and i <= dt.time(10,0,0) or i >= dt.time(10,30,0) and i <= dt.time(14,0,0):
        df['In/Out'] = 'In'
    else:
        df['In/Out'] = 'Out'

I want the code to set the value in a new column to “In” if the time is between two times. The first times are (21:00) & (07:30) the second are (03:00) & (10:00) and the third are (10:30) & (14:00)

If the time is not in those ranges, it should set the value in the new column to “Out”.

Answer

You can simplify:

(21:00) & (07:30) the second are (03:00) & (10:00) 

to:

(21:00) & (10:00) 

so solution is use Series.between with numpy.where:

df=pd.DataFrame({'Time':['0:01:00','8:01:00','2021-08-13 10:19:10','12:01:00',
                        '14:01:00','18:01:01','23:01:00']})

df['Time'] = pd.to_datetime(df['Time']).dt.time


m = (df['Time'].between(dt.time(21,0,0), dt.time(23,23,23)) | 
      df['Time'].between(dt.time(0,0,0), dt.time(10,0,0)) | 
      df['Time'].between(dt.time(10,30,0), dt.time(14, 0,0)))

df['In/Out'] = np.where(m, 'In','Out')
print (df)
       Time In/Out
0  00:01:00     In
1  08:01:00     In
2  10:19:10    Out
3  12:01:00     In
4  14:01:00    Out
5  18:01:01    Out
6  23:01:00     In