首页 > 解决方案 > 比较两次并根据比较返回一个变量

问题描述

我有一个程序可以从网站获取火车出发时间,处理它们并在新窗口中显示它们。现在,我想添加一个更改显示时间颜色的功能。我正在使用以下代码执行此操作:(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 的格式不同

回复:0:07:04

t1: 00:01:00

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

标签: pythoncompare

解决方案


The following converts all of your times into datetime.timedelta objects. Then the comparisons will work to return the different colors. Here is some example code:

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

Another great option is pandas which allows for easy conversion to timedelta and comparison of timedelta objects. After installing pandas (pip install pandas), the following will work (also uses the color() function from above):

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

推荐阅读