Python获取中国节假日数据记录入JSON文件
作者:DriverWon
项目系统内置的日历应用为了提升用户体验,特别设置了在调休日期显示“休”的UI图标功能,那么问题是这些调休数据从哪里来呢?我尝试一种更为智能的方法:Python获取中国节假日数据记录入JSON文件
项目系统内置的日历应用为了提升用户体验,特别设置了在调休日期显示“休”的UI图标功能。那么问题是这些调休数据从哪里来呢?
开发盆友首先访问政府官网,查阅并记录下年度的节假日及调休安排,再录入数据库。作为追求效率与自动化的我(懒),并不认可这种“可爱”的方式。
我尝试一种更为智能的方法:Python获取中国节假日数据记录入JSON文件。
节假日数据获取
获取地址:https://cdn.jsdelivr.net/gh/NateScarlet/holiday-cn@master/年份.json
requests请求即可
import requests
year = 2024
url = f'https://cdn.jsdelivr.net/gh/NateScarlet/holiday-cn@master/{year}.json' # 网址
res = requests.get(url=url, timeout=10) # 发送请求
print(res.json())运行结果:

存入JSON文件
tinydb创建JSON文件,插入获取到的数据
from tinydb import TinyDB
if res.status_code == 200: # 校验是否返回数据
res_data = res.json()
y = res_data.get('year')
d = res_data.get('days')
p = res_data.get('papers')
with TinyDB(f'{year}.json') as db: # 创建/打开tinydb
db.truncate() # 清空数据
db.insert({'year': y, 'days': d, 'papers': p}) # 插入数据运行结果:

节假日数据读取
保存的节假日数据是以年份为名称的不同JSON文件,使用tinydb读取即可
import os
from tinydb import TinyDB
year = 2022
files = [files for root, dirs, files in os.walk(os.path.dirname(os.path.abspath(__file__)))] # 遍历当前文件夹
json_file_list = [os.path.splitext(f)[0] for f in files[0]] # 分割文件名
if str(year) in json_file_list: # 校验是否存在年份数据
with TinyDB(f"{year}.json") as db: # 打开tinydb
print(db.all()) # 获取所有数据
else:
print(f'{year}年数据不存在')运行结果:

封装完整代码
import os
import traceback
import requests
from tinydb import TinyDB
class ChineseHoliday:
"""
中国节假日获取
"""
@staticmethod
def download(year):
"""
获取并保存节假日json数据
获取地址来源:https://github.com/NateScarlet/holiday-cn
:return:
"""
try:
url = f'https://cdn.jsdelivr.net/gh/NateScarlet/holiday-cn@master/{year}.json' # 网址
res = requests.get(url=url, timeout=10) # 发送请求
# print(res.json())
if res.status_code == 200: # 校验是否返回数据
y = res.json().get('year')
d = res.json().get('days')
p = res.json().get('papers')
with TinyDB(f'{year}.json') as db: # 创建/打开tinydb
db.truncate() # 清空数据
db.insert({'year': y, 'days': d, 'papers': p}) # 插入数据
except Exception as e:
info = f"出了点小问题!\n{repr(e)}\n{traceback.format_exc()}"
print(info)
@staticmethod
def get(year):
files = [files for root, dirs, files in os.walk(os.path.dirname(os.path.abspath(__file__)))] # 遍历当前文件夹
json_file_list = [os.path.splitext(f)[0] for f in files[0]] # 分割文件名
if str(year) in json_file_list: # 校验是否存在年份数据
with TinyDB(f"{year}.json") as db: # 打开tinydb
return db.all() # 获取所有数据
return到此这篇关于Python获取中国节假日数据记录入JSON文件的文章就介绍到这了,更多相关Python获取中国节假日数据内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
