首页 > 解决方案 > 如何从 OpenWeatherMap 中检索使用本地时区表示的给定本地日期和时间的天气预报?

问题描述

OpenWeatherMap API 提供免费的 5 天天气预报服务,每天每隔 3 小时提供给定城市的预报报告。

daily_forecast_data = [UTC date:12:00, UTC date:03:00, UTC date:06:00, UTC date:09:00, UTC date:12:00, UTC date:15:00, UTC date:18:00, UTC date:21:00]

如果请求者在悉尼,则 UTC 时间偏移为 +10:00 小时。

所以假设以下 5 天的预测时间窗口:

start = 2021-09-03T12:00:00:00:00
end = 2021-09-08T12:00:00:00:00

如果我提供的 API 端点天气服务器接受该城市本地时区的城市和 ISO8601 日期字符串,我如何从 OpenWeatherMap 检索该城市该日期和时间的正确天气预报?

API 悉尼示例 GET /weather/sydney/?when=2021-09-06T15:00+10:00

这表示查询悉尼 2021 年 9 月 6 日下午 3 点的预测。

城市的 OpenWeatherMap 5 天预报给出了响应,其中 3 小时参考时间戳以 UTC 格式报告了这 5 天。

我是否必须过滤 2021 年 9 月 6 日的 openweathermap 结果集,然后将每个 3 小时时段的参考时间戳转换为当地时间以找到与 T15:00+10:00 最接近的匹配项?

我尝试使用 pyorm Python 库来方便向 openweathermap.org 发出请求:

    owm = OWM("<API KEY>")
    mgr = owm.weather_manager()
    three_h_forecaster = mgr.forecast_at_place("Sydney,AUS", "3h")
    day_iso = "2021-09-06T15:00+10:00:00"

    weather = three_h_forecaster.get_weather_at(day_iso)
    print(f"WEATHER FOR Sydney 3H starts := {three_h_forecaster.when_starts('iso')}")
    print(f"WEATHER FOR Sydney 3H ends := {three_h_forecaster.when_ends('iso')}")
    print(f"Weather for {day_iso} is :: \n{json.dumps(weather.to_dict(), indent=4)}")
    print(f"Weather reference time is: {weather.reference_time('iso')}")
WEATHER FOR Sydney 3H starts := 2021-09-03 15:00:00+00:00
WEATHER FOR Sydney 3H ends := 2021-09-08 12:00:00+00:00
Weather for 2021-09-06T15:00+10:00:00 is :: 
{
    "reference_time": 1630908000,
    "sunset_time": null,
    "sunrise_time": null,
    "clouds": 32,
    "rain": {},
    "snow": {},
    "wind": {
        "speed": 10.42,
        "deg": 193,
        "gust": 14.76
    },
    "humidity": 53,
    "pressure": {
        "press": 1027,
        "sea_level": 1027
    },
    "temperature": {
        "temp": 287.64,
        "temp_kf": 0,
        "temp_max": 287.64,
        "temp_min": 287.64,
        "feels_like": 286.53
    },
    "status": "Clouds",
    "detailed_status": "scattered clouds",
    "weather_code": 802,
    "weather_icon_name": "03d",
    "visibility_distance": 10000,
    "dewpoint": null,
    "humidex": null,
    "heat_index": null,
    "utc_offset": null,
    "uvi": null,
    "precipitation_probability": 0.02
}
Weather reference time is: 2021-09-06 06:00:00+00:00

我使用这个正确吗?我注意到报告的参考时间是2021-09-06 06:00:00+00:00....

标签: pythonopenweathermap

解决方案


推荐阅读