You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Python脚本通过CDS API下载ERA5数据时遇重复月份错误求助

解决CDS API下载ERA5数据时的"Duplicate value for month"错误

错误原因分析

  • ERA5数据时间范围限制:ERA5再分析数据仅从1959年开始提供,你请求的1945年无可用数据,Mars服务器处理无效年份时抛出了带有误导性的"重复月份"错误。
  • 日期参数不合理:原请求中每个月都包含31天,但2月、4月、6月、9月、11月不存在31号,这也会导致请求解析失败。

修正后的代码

调整年份范围至ERA5可用区间,并针对每个月份设置正确的天数,同时分月请求以降低单次请求的数据量:

import cdsapi
import urllib3

urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

c = cdsapi.Client()

# 定义平年各月份的天数
month_days = {
    '01': 31, '02': 28, '03': 31,
    '04': 30, '05': 31, '06': 30,
    '07': 31, '08': 31, '09': 30,
    '10': 31, '11': 30, '12': 31
}

# 遍历ERA5可用的年份范围(1959-2021)
for year in range(1959, 2022):
    # 处理闰年2月的天数
    if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
        month_days['02'] = 29
    else:
        month_days['02'] = 28
    
    # 分月请求数据
    for month in month_days.keys():
        # 生成当月的天数列表,格式化为两位数字字符串
        days = [f"{day:02d}" for day in range(1, month_days[month] + 1)]
        c.retrieve(
            'reanalysis-era5-single-levels',
            {
                'variable': 'total_precipitation',
                'format': 'netcdf',
                'year': str(year),
                'month': month,
                'day': days,
                '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',
                ],
                'area': [90, -180, -90, 180], # 全球范围
            },
            f'era5_{year}_{month}_precipitation.nc',
        )

额外注意事项

  • 分月请求比全年请求更稳定,避免因单次数据量过大被服务器拒绝或超时。
  • 确保已登录CDS官网,搜索并进入ERA5数据页面,同意数据使用条款,否则无法下载数据。
  • 检查本地~/.cdsapirc配置文件,确保API密钥和服务URL正确无误。

内容的提问来源于stack exchange,提问作者shibashiba

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 02:32:50