我有一个程序,该程序从网站获取火车发车时间,进行处理并将它们显示在新窗口中。现在,我想添加一个功能来更改显示时间的颜色。我正在使用以下代码执行此操作: (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
答案 0 :(得分:1)
以下内容将您所有的时间都转换为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对象。在安装了熊猫(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