Search code examples
pythonpandasdataframepython-datetime

Is there a way to get datetime ranges based on the value of another column in a pandas dataframe?


I'm sure the question was not descriptive enough, but here is what I'm looking for. I have 3 columns in my dataframe. Two are datetimes and the other is a float that contains either a 1 or 0. It is a status column and 1 means on 0 means off obviously. I need to find out whether I am able to get the different ranges of times when the status was 0 and 1.

Can I do this with pandas, or do I need to try something else? Sample data from dataframe

Dataframe name is uptime. Columns in order from left to right are time_utc, state, local_time. I'm really not concerned with time_utc, so you can disregard that. This is my first question on here as I wasn't really even sure how to google this question. Please let me know if more information is required, and I will provide what I can. Thank you in advance for any response lol.

Edit:

In the table shown in the picture, you can see it was down from 04:54:27 to 5:01:21, which is when it came back up, and was back down by 05:02:16. It then went back down until 05:09:24, where it was back up until 05:11:50. I am just trying to write something that can pull those ranges, and maybe store them in another dataframe.

Edit:

I am doing a terrible job of asking this question, I know, but hopefully this picture of example output will help.


Solution

  • If its by time here you go, and i dont know the column names so i am just gonna throw in a random one

    selecte_df = df.loc[(df['time_utc'].dt.hour >= 6) & (df['time_local'].dt.hour <= 8) & (df['state'] == 1)] # Get hour range and state
    
    selected_df.to_csv('new.csv', index=False) # Write to new csv