用 Python批量下载 ERA5-Land 土壤湿度数据cdsapi 实战教程一、准备工作1. 安装依赖pipinstallcdsapi2. 配置 CDS API Key非常重要在你的用户目录创建~/.cdsapirc内容如下url:https://cds.climate.copernicus.eu/api key: your-user-id:your-api-keyAPI Key 在这里申请https://cds.climate.copernicus.eu/二、核心思路下载 ERA5-Land 数据时必须指定年year月month日day小时time变量variable但问题是 不同月份天数不同尤其 2 月闰年所以我们写了一个函数三、核心代码解析自动计算每个月天数importcalendardefget_days_in_month(year,month):获取某月所有日期自动处理闰年ifmonth2:1,calendar.monthrange(year,month)[1]1)]✔ 作用确保请求 CDS 时不会因为日期错误报错。四、批量下载 ERA5-Land全年数据importcdsapidefdownload_era5_land_data(start_year,end_year):批量下载ERA5-Land数据datasetreanalysis-era5-landclientcdsapi.Client()foryearinrange(start_year,end_year1):formonthinrange(1,13):daysget_days_in_month(year,month)request{variable:[volumetric_soil_water_layer_1],year:str(year),month:str(month).zfill(2),day:days,time:[00:00],data_format:netcdf,download_format:unarchived}print(f开始下载{year}-{str(month).zfill(2)}月的数据...)# 下载数据并保存到指定路径client.retrieve(dataset,request).download(fE:/2025/SMI_{year}_{str(month).zfill(2)}.nc)print(f{year}-{str(month).zfill(2)}月的数据下载完成.)# 设置下载数据的起始年份和结束年份start_year2025end_year2025# 调用下载函数download_era5_land_data(start_year,end_year)五、下载单月示例8月如果你只想下载某个月可以用更简洁版本pythondef downloadera5landdatafor_august(year):datasetreanalysis-era5-landclientcdsapi.Client()month8daysget_days_in_month(year,month)request{variable:[volumetric_soil_water_layer_1],year:str(year),month:08,day:days,time:[00:00],data_format:netcdf,download_format:unarchived}print(f开始下载{year}-08)client.retrieve(dataset,request).download(fE:/2025/SMI_{year}_08.nc)print(下载完成)完整代码importcdsapiimportcalendardefget_days_in_month(year,month):根据年份和月份获取该月的天数自动处理闰年情况ifmonth2:# 2月判断是否闰年if(year%40andyear%100!0)or(year%4000):return[str(i)foriinrange(1,30)]# 闰年2月有29天else:return[str(i)foriinrange(1,29)]# 平年2月有28天else:# 获取其他月份的天数return[str(i)foriinrange(1,calendar.monthrange(year,month)[1]1)]defdownload_era5_land_data_for_august(year):下载特定年份 8 月的数据datasetreanalysis-era5-landclientcdsapi.Client()month8# 只下载8月的数据daysget_days_in_month(year,month)request{variable:[volumetric_soil_water_layer_1],year:str(year),month:str(month).zfill(2),day:days,time:[00:00],data_format:netcdf,download_format:unarchived}print(f开始下载{year}-08 月的数据...)# 下载数据并保存到指定路径client.retrieve(dataset,request).download(fE:/2025/SMI_{year}_08.nc)print(f{year}-08 月的数据下载完成.)# 设置下载数据的年份year2025# 调用下载函数download_era5_land_data_for_august(year)