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

如何从给定OpenWeatherMap API返回数据中获取温度及华氏温度?

获取OpenWeatherMap API中的温度(含华氏度转换)

嘿,我来帮你搞定这个问题——从OpenWeatherMap的API返回数据里提取温度,再转成华氏度其实超简单,一步步来:

第一步:提取原始温度数据

先看你给出的API返回结果,main对象里的temp字段就是当前环境温度,注意:默认返回的是开尔文(K)单位,同时还附带了temp_min(最低温)和temp_max(最高温),同样是开尔文单位。

给你几个常用编程语言的提取示例:

  • JavaScript(假设你已经通过fetch/axios拿到了响应对象response):
    // 提取当前温度、最低温、最高温(开尔文)
    const currentTempKelvin = response.main.temp;
    const minTempKelvin = response.main.temp_min;
    const maxTempKelvin = response.main.temp_max;
    
  • Python(假设你用requests库把返回数据存在data字典里):
    # 提取当前温度、最低温、最高温(开尔文)
    current_temp_kelvin = data['main']['temp']
    min_temp_kelvin = data['main']['temp_min']
    max_temp_kelvin = data['main']['temp_max']
    

第二步:转换为华氏度(°F)

OpenWeatherMap默认不会直接返回华氏度,所以需要手动转换,用这个标准公式就行:
°F = (开尔文温度 - 273.15) × 9/5 + 32
(也可以用等价的简化公式:°F = 开尔文温度 × 9/5 - 459.67,计算结果完全一致)

同样给你代码示例,还加了保留两位小数的处理,让结果更美观:

  • JavaScript:
    // 转换为华氏度并保留两位小数
    const currentTempFahrenheit = (currentTempKelvin - 273.15) * 9/5 + 32;
    const roundedTempF = currentTempFahrenheit.toFixed(2);
    console.log(`当前温度:${roundedTempF}°F`);
    
  • Python:
    # 转换为华氏度并保留两位小数
    current_temp_fahrenheit = (current_temp_kelvin - 273.15) * 9/5 + 32
    rounded_temp_f = round(current_temp_fahrenheit, 2)
    print(f"当前温度:{rounded_temp_f}°F")
    

小技巧:直接请求华氏度结果

其实你完全可以省掉转换步骤——在调用OpenWeatherMap API的时候,给请求URL加上&units=imperial参数,这样返回的temp字段直接就是华氏度了!比如请求URL长这样:

https://api.openweathermap.org/data/2.5/weather?q=Huntington%20Station&appid=YOUR_API_KEY&units=imperial

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 04:38:43