Comparing two times and return a variable based on comparison

Viewed 34

I have a program that takes train departure times from a website, processes them and displays them in a new window. Now, I would like to add a feature that changes the colour of the times displayed. I am doing this with the following code: (res&res2 are the departure times)

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"

Now my problem is that this code always returns "green", no matter what the times are. I've tried to convert both times into strings and then compare them, I've tried to convert both to datetime and compare them and I've tried to pick only the minutes and compare those - which didn't work because res is a timedelta.

My guess is that this is because of different formats of res and t1 / t2

res: 0:07:04

t1: 00:01:00

This is a link to the .py file of my whole code https://drive.google.com/file/d/1NK4bYgstWKumRI95AD1nP9sHRTfEhXnj/view?usp=sharing

1 Answers

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
Related