I Have a dataframe(df1) which has the time values in HH:MM:SS
format .
df1
col_a | col_b | col_c | col_d
00:00:15|00:01:15|00:01:30|00:02:30
00:02:45|00:04:00|00:05:30|00:06:30
I have a value stored in a variable check_time="00:01:00"
I need to check if the value is within the range of two column.
As the check_time
is between col_a
and col_b
if its present then i would need the below output.
I tried df1.loc[((df1['Col_a']>check_time) & (df1['Col_b']<=check_time))]
but i am not getting the desired output .
Output:
Col_b
00:01:15
CodePudding user response:
If by range you mean the time difference between Col_a and Col_b then you need to find first the diff, so something like this:
import datetime as dt
start_dt = dt.datetime.strptime(df1['Col_a'], '%H:%M:%S')
end_dt = dt.datetime.strptime(df1['Col_b'], '%H:%M:%S')
diff = (end_dt - start_dt)
check_time ="00:01:00"
check_time_dt=dt.datetime.strptime(check_time, '%H:%M:%S')
if check_time_dt/60 <= diff/60:
<do something>
CodePudding user response:
In order to be able to compare time values you will have to convert your string representation into a datetime object. You can use datetime's class strptime() method.
from datetime import datetime
check_time_obj = datetime.strptime(check_time, '%H:%M:%S')
After which you can handle your comparisons like so:
datetime.strptime(df1['Col_a'], '%H:%M:%S') < check_time_obj