使用日期时间过滤 json 结果 - 排除周末 - Python

Filter json result with datetime - exclude weekends - Python

考虑这段代码:

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

此代码从 response 中获取 API 响应,其中包含从 1999 年至今的一系列货币汇率,我需要的是了解如何过滤这些数据,通过从所有这些年中获取 date,但不包括周末。

这个 api url 的响应是这样的:

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

我不知道我是不是在解释自己,我正在获取所有历史数据,但我需要实际获取这个,不包括周末。

我知道 datetime 有一个 isweekday 功能,但我不太确定在这种情况下如何使用它。

有什么想法吗?

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().

所以我想你可以这样做:

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

如果我的理解是正确的 - 您希望费率仅对应于工作日的日期。 (有错请指正)

在这种情况下,您可以使用日期时间 day.weekday() 方法。

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

所以,用法是这样的 -

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 用于我在上述代码中完成的日期字符串格式设置。