如何将时间值与 pandas 中列中的所有时间值进行比较?

How do I compare a time value to all the time values in a column in pandas?

我想对数据框中的列应用条件。该列具有 HH:MM:SS 格式的时间值,我想将它与固定时间值(阈值)进行比较,但出现错误。将阈值转换为 datetime.datetime.strptime 给我错误。我想问的是 - 为了比较任何两个时间值,我该如何存储它们或将它们转换成什么以便进行比较?阈值是字符串,列值是 datetime.time 格式。

当我这样做时-

threshold = datetime.datetime.strptime('1:04:00','%H:%M:%S').time()  
df_styled = df.style.apply(lambda x:['background:red' if x > threshold else "background:white" for x in df['Total Time']], axis=0) 

我得到 -

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

当我这样做时-

threshold = datetime.datetime.strptime('1:04:00','%H:%M:%S')
df['Total Time'] = df['Total Time'].apply(lambda x: datetime.datetime.strptime(x,'%H:%M:%S'))
df_styled = df.style.apply(lambda x:['background:red' if x > threshold else 'background:white' for x in df['Total Time']], axis=0)

我收到错误

TypeError: strptime() argument 1 must be str, not datetime.time

您可以比较 Timedelta and to_timedelta 创建的时间增量:

threshold = pd.Timedelta('1:04:00')
df['Total Time'] = pd.to_timedelta(df['Total Time'].astype(str))

df_styled = df.style.apply(lambda x:['background:red' if x > threshold else "background:white" for x in df['Total Time']], axis=0) 

编辑:问题数据的解决方案:

df['Total Time'] = pd.to_timedelta(pd.to_datetime(df['Total Time'].astype(str)).dt.strftime('%H:%M:%S'))