I'm trying to create time slot starting from time column in my df which have the following structure:
artist_name;ms_played;track_name;...date;time;week_day
Taylor Swift;35260;Wildest Dreams;...;2021-01-25;07:55;0
Edward Sharpe & The Magnetic Zeros;...2021-01-25;15:34;0
.....
for example, all time between 6am and 8am I want it to fall within the time slot 6-8 and so on for the others. So far I have unfortunately not been able to write anything, so any suggestions will be welcome. Thanks for the replies.
You can do so with the help of the following code:
import pandas as pd
df = pd.DataFrame({'name':['Taylor Swift','Edward Sharpe & The Magnetic Zeros'],'time':['7:55','15:34']})
def timeSlot(x):
hr = pd.to_datetime(x).hour
if hr == 23:
upper = 0
lower = hr-1
elif hr == 0:
upper = hr+1
lower = 23
else:
upper = hr+1
lower = hr-1
return f'{lower}-{upper}'
df['slot'] = df['time'].apply(lambda x: timeSlot(x))