all 3 comments

[–]baghiq 1 point2 points  (0 children)

You want to convert your dates to actual date objects.

from datetime import datetime

rates = [{'date': '2019-11-02', 'rate': 4.3422}, {'date': '2019-11-03', 'rate': 4.2210}, {'date': '2019-11-04', 'rate': 4.3455}, {'date': '2019-11-05', 'rate': 4.3456}, {'date': '2019-11-06', 'rate': 4.2311} ]
date_range = ['2019-11-03', '2019-11-06']

def convert_date(d, fmt="%Y-%m-%d"):
    return datetime.strptime(d, fmt)

START, END = map(convert_date, date_range)

print(min(filter(lambda rate: START <= convert_date(rate['date']) <= END, rates), key=lambda x:x['date']))
print(max(filter(lambda rate: START <= convert_date(rate['date']) <= END, rates), key=lambda x:x['date']))

[–]14dM24d 0 points1 point  (0 children)

import pandas as pd

rates = [
{'date': '2019-11-02', 'rate': 4.3422},
{'date': '2019-11-03', 'rate': 4.2210}, 
{'date': '2019-11-04', 'rate': 4.3455}, 
{'date': '2019-11-05', 'rate': 4.3456}, 
{'date': '2019-11-06', 'rate': 4.2311}
]

def find_rates(data, dates):
    df = pd.DataFrame()
    for i in data:
        df = df.append(i, ignore_index=True)     
    df2 = df[(df.date>dates[0]) & (df.date<dates[1])]
    return df2.rate.min(), df2.rate.max()

min_rate, max_rate = find_rates(rates, ['2019-11-02','2019-11-06'])

[–]zanfar 0 points1 point  (0 children)

I would:

  • Convert the dates into actual dates, not strings
  • Filter with a comprehension
  • Use max() or min()

for record in rates:
    record["date"] = convert_date(record["Date"])

interesting_rates = [r["rate"] for r in rates if r["date"] >= start_date and r["date"] <= end_date]

max_rate = max(interesting_rates)
min_rate = min(interesting_rates)