【问题标题】:Python to check if a time (HH:mm:ss) is present within two columns valuesPython检查时间(HH:mm:ss)是否存在于两列值中
【发布时间】:2021-12-02 15:20:59
【问题描述】:

我有一个数据帧(df1),它的时间值采用HH:MM:SS 格式。

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

我有一个值存储在变量check_time="00:01:00" 中,我需要检查该值是否在两列的范围内。

由于check_time 介于col_a 和col_b 之间,如果它存在,那么我需要以下输出。

我尝试了df1.loc[((df1['Col_a']>check_time) & (df1['Col_b']<=check_time))],但没有得到想要的输出。

输出:

Col_b

00:01:15

【问题讨论】:

  • 这是想要的输出还是不需要的输出?
  • 这是所需的输出

标签: python python-3.x dataframe between


【解决方案1】:

如果你的范围是指 Col_a 和 Col_b 之间的时间差,那么你需要先找到差异,所以像这样:

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>

【讨论】:

  • 不,不是时差。我想检查 col A 和 col B 之间的 check_time 值 id 如果是,那么我需要在条件匹配的特定位置返回 B 列值
【解决方案2】:

为了能够比较时间值,您必须将字符串表示形式转换为日期时间对象。您可以使用 datetime 的类 strptime() 方法。

from datetime import datetime
check_time_obj = datetime.strptime(check_time, '%H:%M:%S')

之后你可以像这样处理你的比较:

datetime.strptime(df1['Col_a'], '%H:%M:%S') < check_time_obj

【讨论】:

  • 我正在与日期时间对象进行比较
猜你喜欢
  • 1970-01-01
  • 2019-07-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-04
  • 2015-03-06
  • 1970-01-01
相关资源
最近更新 更多