复制到本地项目中,替换dataset和request为自己需要的产品即可。
import cdsapi
import os
from datetime import datetime
# 自定义文件夹路径
custom_folder = r"C:\Users\73955\Desktop\ERA5_ZTD"
# 创建该文件夹(如果不存在)
if not os.path.exists(custom_folder):
os.makedirs(custom_folder)
# 判断是否为闰年的函数
def is_leap_year(year):
# 如果能被400整除,或者能被4整除但不能被100整除,则是闰年
if (year % 400 == 0) or (year % 4 == 0 and year % 100 != 0):
return True
return False
# 用户定义的日期范围
start_year = 2020
start_month = 1
start_day = 1
end_month = 12
end_day = 31
# 每月的天数(考虑闰年)
def get_days_in_month(year, month):
if month == 2:
return 29 if is_leap_year(year) else 28
elif month in [4, 6, 9, 11]:
return 30
else:
return 31
# 遍历日期范围
current_year = start_year
current_month = start_month
current_day = start_day
while current_year < start_year or (current_year == start_year and current_month < end_month) or (current_year == start_year and current_month == end_month and current_day <= end_day):
# 生成日期字符串,如 2024_01_01
date_str = f"{current_year}_{str(current_month).zfill(2)}_{str(current_day).zfill(2)}"
# 设置请求参数
dataset = "reanalysis-era5-pressure-levels"
request = {
"product_type": ["reanalysis"],
"variable": [
"geopotential",
"relative_humidity",
"specific_humidity",
"temperature"
],
"year": [str(current_year)],
"month": [str(current_month).zfill(2)],
"day": [str(current_day).zfill(2)],
"time": [
"00:00", "01:00", "02:00",
"03:00", "04:00", "05:00",
"06:00", "07:00", "08:00",
"09:00", "10:00", "11:00",
"12:00", "13:00", "14:00",
"15:00", "16:00", "17:00",
"18:00", "19:00", "20:00",
"21:00", "22:00", "23:00"
],
"pressure_level": [
"1", "2", "3",
"5", "7", "10",
"20", "30", "50",
"70", "100", "125",
"150", "175", "200",
"225", "250", "300",
"350", "400", "450",
"500", "550", "600",
"650", "700", "750",
"775", "800", "825",
"850", "875", "900",
"925", "950", "975",
"1000"
],
"data_format": "netcdf",
"download_format": "unarchived",
"area": [54, 70, 3, 140]
}
# 初始化CDS客户端
client = cdsapi.Client()
# 设置文件名,按日期格式命名
output_filename = f"ERA5_{date_str}.nc"
output_path = os.path.join(custom_folder, output_filename)
print(f"开始下载: {output_filename}")
# 下载并保存
client.retrieve(dataset, request, output_path)
print(f"下载的文件已保存到: {output_path}")
# 处理日期:增加一天
current_day += 1
if current_day > get_days_in_month(current_year, current_month):
current_day = 1
current_month += 1
if current_month > 12:
current_month = 1
current_year += 1