0

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?

NeoVe
  • 3,857
  • 8
  • 54
  • 134

2 Answers2

2

from https://docs.python.org/3/library/datetime.html :

date.weekday()
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, a Wednesday. See also isoweekday().

So I guess you could do something like:

import datetime
dataYear = "year from your data"
dataMonth = "Month from your data"
dataDay = "Day from your data"
dateToCheck = datetime.date(dataYear,dataMonth,dataDay)
if(dateToCheck.weekday() == 5 or dateToCheck.weekday() == 6):
     isWeekend = true
Sharku
  • 1,052
  • 1
  • 11
  • 24
1

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.

  • Thank You, this seems to do the trick, but I'm getting ´ValueError: time data '1999-01-01' does not match format '%Y-%b-%d', seems to be Okay with me, does that parameter need also the hour and minutes? ´ – NeoVe Aug 18 '18 at 09:45
  • @NeoVe My bad. Try "%Y-%m-%d". You can refer to this link to understand what "%Y-%m-%d" exactly means - strftime.org – Shubham Sinha Aug 19 '18 at 13:49