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

如何基于当前时间从Elspotprices API输出对应SpotPriceDKK

实现电力现货价格时间匹配功能的完整方案

1. 修复代码基础问题

你的代码缺少datetime模块的导入,首先补充:

from datetime import datetime

2. 分析API返回数据结构

API返回的records数组中,每条记录包含核心字段:

  • HourDK:价格对应的小时时间段(ISO格式字符串,如2024-05-20T14:00:00)
  • PriceArea:价格区域标识(DK1/DK2)
  • SpotPriceDKK:对应区域的现货价格(丹麦克朗)

3. 编写时间匹配逻辑

核心思路是将当前时间格式化为与HourDK完全一致的格式,再遍历记录找到匹配项:

import requests
from datetime import datetime

# 调用API获取数据
response = requests.get(
    'https://api.energidataservice.dk/dataset/Elspotprices?filter={"PriceArea":["DK1","DK2"]}&limit=50')
result = response.json()
records = result.get('records', [])

# 生成当前时间的匹配格式(精确到整点)
now = datetime.now()
current_time_str = now.strftime("%Y-%m-%dT%H:00:00")

# 遍历记录查找匹配的价格
matched_records = [r for r in records if r['HourDK'] == current_time_str]

if matched_records:
    for record in matched_records:
        print(f"区域{record['PriceArea']} 当前时间({current_time_str})的现货价格:{record['SpotPriceDKK']} DKK")
else:
    print(f"未找到当前时间({current_time_str})对应的现货价格记录")

4. 关键细节说明

  • 时间格式统一:必须将当前时间转换为与HourDK完全相同的ISO格式,才能确保精确匹配。
  • 多区域处理:API同时返回DK1和DK2的记录,可通过遍历输出两个区域价格,也可添加if record['PriceArea'] == 'DK1'筛选单个区域。
  • 异常处理:添加无匹配记录的提示,避免程序静默失败。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 07:40:23