Skip to main content
 首页 » 编程设计

python之比较两次并返回一个基于比较的变量

2024年12月31日9java哥

我有一个程序可以从网站上获取火车出发时间,对其进行处理并在新窗口中显示。现在,我想添加一个更改显示时间颜色的功能。我正在使用以下代码执行此操作: (res&res2为出发时间)

t1 = time(0,1,0) 
t2 = time(0,2,0) 
def color(): 
    f = get_resp() 
    g = f[1] 
    res = g[0] 
    res2 = str(res) 
 
    if res2 < t1: 
        return  "red" 
    elif res2 < t2: 
        return  "orange" 
    elif res2 > t2: 
        return "green" 

现在我的问题是这段代码总是返回“绿色”,无论什么时候。 我尝试将两个时间都转换为字符串然后进行比较,我尝试将两者都转换为日期时间并进行比较,我尝试只选择分钟并进行比较——这没有用,因为 res 是一个时间增量。

我猜这是因为res和t1/t2的格式不同

res: 0:07:04

t1: 00:01:00

这是我整个代码的 .py 文件的链接 https://drive.google.com/file/d/1NK4bYgstWKumRI95AD1nP9sHRTfEhXnj/view?usp=sharing

请您参考如下方法:

以下将您所有的时间转换为 datetime.timedelta 对象。然后比较将返回不同的颜色。下面是一些示例代码:

from datetime import datetime, timedelta, time 
 
def to_timedelta(t): 
  t_dt = datetime.strptime(str(t),"%H:%M:%S") 
  t_delta = timedelta(hours=t_dt.hour, 
                      minutes=t_dt.minute, 
                      seconds=t_dt.second) 
  return t_delta 
 
def color(): 
  # Modified variable names to use the timedelta variables 
  if res_td < t1_td: 
    return  "red" 
  elif res_td < t2_td: 
    return  "orange" 
  elif res_td > t2_td: 
    return "green" 
 
t1 = time(0,1,0) 
t2 = time(0,2,0) 
 
t1_td = to_timedelta(t1) 
t2_td = to_timedelta(t2) 
 
# This returns "red" 
res = time(0,0,4) 
res_td = to_timedelta(res) 
color1 = color() 
print color1 
 
# This returns "orange" 
res = time(0,1,0) 
res_td = to_timedelta(res) 
color2 = color() 
print color2 
 
# This returns "green" 
res = time(0,7,4) 
res_td = to_timedelta(res) 
color3 = color() 
print color3 

另一个不错的选择是 pandas,它可以轻松转换为 timedelta 并比较 timedelta 对象。安装 pandas (pip install pandas) 后,以下将起作用(也使用上面的 color() 函数):

import pandas as pd 
 
def to_timedelta_pd(t): 
  # Return pandas timedelta from passed datetime.time object 
  t_delta = pd.to_timedelta(str(t)) 
  return t_delta 
 
t1 = time(0,1,0) 
t2 = time(0,2,0) 
 
t1_td = to_timedelta_pd(t1) 
t2_td = to_timedelta_pd(t2) 
 
# This returns "red" 
res = time(0,0,4) 
res_td = to_timedelta_pd(res) 
color1 = color() 
print color1 
 
# This returns "orange" 
res = time(0,1,0) 
res_td = to_timedelta_pd(res) 
color2 = color() 
print color2 
 
# This returns "green" 
res = time(0,7,4) 
res_td = to_timedelta_pd(res) 
color3 = color() 
print color3