import requests
import json
import requests.packages.urllib3.util.ssl_
import os
import time
requests.packages.urllib3.util.ssl_.DEFAULT_CIPHERS = 'ALL' # 防止SSL限制
def isExist(timestr,save_file_path):
with open(save_file_path, 'a+') as f:
f.seek(0)
lines = f.readlines()
if timestr in lines:
return 1
else:
return 0
def get_trading_date(_year_i,_month_i,save_file_path):
"""通过爬虫抓取深交所的交易日历
:param month_date: 日期,例 2020-01、2022-12
"""
month_date = "{}-{}".format(_year_i, _month_i + 1)
target_url = "http://www.szse.cn/api/report/exchange/onepersistenthour/monthList?month={}".format(month_date)
send_headers = {
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.0.0 Safari/537.36",
"Connection": "keep-alive",
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
"Accept-Language": "zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7"}
time.sleep(2) # 限制频率
req = requests.get(target_url, headers=send_headers)
json_state = json.loads(req.text)
for dict_value in json_state['data']:
#保存结果:工作日非交易日
date_str = dict_value['jyrq']
if dict_value['jybz'] == "1":
with open(save_file_path, 'a') as file:
file.write(date_str)
file.write("\n")
return 0
def main():
#timestr为需要判断的日期,默认为当天
timestr = time.strftime('%Y-%m-%d',time.localtime(time.time()))+'\n'
year = time.strftime('%Y',time.localtime(time.time()))
save_file_path = year + "交易日.txt"
#1.判断文件存在后,返回是否为交易日
if(os.path.isfile(save_file_path)):
return isExist(timestr,save_file_path)
#2.更新文件,每年一次
print("无本地文件,进行下载")
for _month_i in range(12):
get_trading_date(year, _month_i, save_file_path)
#3.判断是否工作日非交易日
return isExist(timestr,save_file_path)
if __name__ == '__main__':
res = main()
if(1 == res):
print("当天是交易日")
判断指定日期是否为交易日-python
于 2023-07-10 21:00:00 首次发布