Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Applying conditional statement to time column

I have a python code that converts one column df[r_t] to utc:

   df.r_t = pd.to_datetime(df.r_t)

And generate another column for time:

    df['time'] = (df['r_t'].dt.time)

My resulting column is as follows:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

|         r_t             |   time    |
| ----------------------- | --------- |
| 2022-05-28 00:00:00+00  | 00:00:00  |
| 2022-05-28 00:00:01+00  | 00:00:01  |
| 2022-05-28 00:00:02+00  | 00:00:02  |

We have 20k rows.
Now what am trying to do is generate a night and day dataframe: Like

   time_1 = pd.to_datetime('04:00:00')
   time_2 = pd.to_datetime('09:00:00')
   df_day = df[(df['time'] > time_1) & (df['time'] <= time_2)]
   df_night = not in(df[(df['time'] > time_1) & (df['time'] <= time_2)])

I know am doing this wrong as i get error:

    TypeError: '>' not supported between instances of 'datetime.time' and 'Timestamp'

Can someone point me in the right direction. Thanks!

>Solution :

Try:

time_day = pd.to_datetime("04:00:00").time()
time_night = pd.to_datetime("09:00:00").time()

mask = (df["time"] > time_day) & (df["time"] <= time_night)

df_day = df[mask]
df_night = df[~mask]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading