pythonjsonfixer.io

Filter json result with datetime - exclude weekends - Python


Consider this code:

def getHistoricRates():
rates = []
response = urlopen('http://data.fixer.io/api/1999-01-01?access_key=my_key')
data = response.read()
rdata = json.loads(data.decode(), parse_float=float) 
rates_from_rdata = rdata.get('rates', {})
for rate_symbol in ['USD', 'GBP', 'HKD', 'AUD']:
    try:
        rates.append(rates_from_rdata[rate_symbol])

    except KeyError:
        logging.warning('rate for {} not found in rdata'.format(rate_symbol)) 
        pass
return rates

This code, takes from response an API response, with a series of currency exchange rates, from 1999 until now, what I need, is to understand, how can I filter this data, by taking the date from all of these years, but, excluding weekends.

The response from this api url is something like this:

"success":true,"timestamp":915235199,"historical":true,
"base":"EUR","date":"1999-01-01",
"rates":{"ANG":2.086282,"AUD":1.918776,... other currencies}

I don't know if I'm explaining myself, I'm getting all the historical data, but I need to actually get this, excluding weekends.

I know that datetime has a isweekday function, but I'm not really sure on how to use it in this case.

Any ideas?


Solution

  • If what I am understanding is correct - you want rates corresponding to only dates that lie on a weekday. (Correct me if I am wrong)

    In such a case, you can use the datetime day.weekday() method.

    day.weekday() explanation - Return the day of the week as an integer, where Monday is 0 and Sunday is 6. For example, date(2002, 12, 4).weekday() == 2

    So, usage would be something like this -

    date_str = "1999-01-01"
    if datetime.datetime.strptime(date_str,"%Y-%b-%d").weekday()<5: #Converting to a datetime object after which weekday() method call will return <5 for a weekday
        rates = getHistoricRates(date_str) #pass the date_str in the function
    

    Refer here for date string formatting that I have done in the above code.