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

基于Google Places与OpenWeatherMap的多时间维度天气函数实现问询

解决方案:多时间维度天气信息整合函数开发

看起来你已经搞定了最关键的数据源部分——通过Google Places拿到了异地的经纬度和UTC偏移,又用OpenWeatherMap获取了核心的天气时间数据,接下来就是把这些零散的时间统一转换成需要的格式,封装成函数即可。我来拆解下具体步骤:

核心逻辑:时间转换是关键

所有的时间数据(日出、日落、预报时间)都是UTC格式,我们需要基于异地的UTC偏移量把它们转换成异地本地时间,同时还要获取本地时间,核心就是利用时区偏移做时间加减法。

1. 获取本地时间

这一步最简单,直接用你所用编程语言的原生本地时间API即可,比如:

  • Python:datetime.datetime.now()(带本地时区信息)
  • JavaScript:new Date()(自动关联本地时区)

2. 计算异地本地时间

利用你拿到的utc_offset(注意Google Places返回的是秒数),结合当前UTC时间来计算:

import datetime

# 假设从Places API拿到的utc_offset是+7200秒(即东2区)
utc_offset_sec = 7200
remote_timezone_offset = datetime.timedelta(seconds=utc_offset_sec)

# 当前UTC时间 + 偏移量 = 异地本地时间
utc_now = datetime.datetime.utcnow()
remote_local_time = utc_now + remote_timezone_offset

3. 转换异地日出/日落时间

OpenWeatherMap返回的日出、日落是UTC时间戳,先转成UTC datetime对象,再加偏移量即可:

# 假设从OWM拿到的sunrise是1696123200(UTC时间戳)
sunrise_utc = datetime.datetime.utcfromtimestamp(1696123200)
remote_sunrise = sunrise_utc + remote_timezone_offset

# 日落时间同理
sunset_utc = datetime.datetime.utcfromtimestamp(1696180800)
remote_sunset = sunset_utc + remote_timezone_offset

4. 处理天气报告发布时间

同样基于UTC时间戳转换,还可以顺便转成本地时间方便对比:

report_utc = datetime.datetime.utcfromtimestamp(owm_data['dt'])
# 转成异地本地时间
report_remote_time = report_utc + remote_timezone_offset
# 转成本地时间(用本地时区的UTC偏移)
local_timezone_offset = datetime.timedelta(seconds=time.localtime().tm_gmtoff)
report_local_time = report_utc + local_timezone_offset

5. 整合3小时间隔预报时间

遍历OWM返回的24小时预报列表,逐个把每个预报的UTC时间转成异地本地时间,同时保留对应的天气信息:

forecast_list = []
for item in owm_data['list']:
    forecast_utc = datetime.datetime.utcfromtimestamp(item['dt'])
    forecast_remote_time = forecast_utc + remote_timezone_offset
    forecast_list.append({
        "remote_time": forecast_remote_time.strftime("%Y-%m-%d %H:%M"),
        "weather": item['weather'][0]['description'],
        "temp": item['main']['temp']
    })

6. 封装成完整函数

把上面的逻辑整合到一个函数里,输入是Places和OWM的返回数据,输出是包含所有所需时间的结构化数据:

import datetime
import time

def generate_weather_time_data(places_api_data, owm_api_data):
    # 提取核心参数
    utc_offset_sec = places_api_data['utc_offset']
    remote_timezone_offset = datetime.timedelta(seconds=utc_offset_sec)
    
    # 1. 本地时间
    local_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    
    # 2. 异地本地时间
    utc_now = datetime.datetime.utcnow()
    remote_local_time = (utc_now + remote_timezone_offset).strftime("%Y-%m-%d %H:%M:%S")
    
    # 3. 异地日出/日落时间
    sunrise_utc = datetime.datetime.utcfromtimestamp(owm_api_data['sys']['sunrise'])
    remote_sunrise = (sunrise_utc + remote_timezone_offset).strftime("%Y-%m-%d %H:%M")
    sunset_utc = datetime.datetime.utcfromtimestamp(owm_api_data['sys']['sunset'])
    remote_sunset = (sunset_utc + remote_timezone_offset).strftime("%Y-%m-%d %H:%M")
    
    # 4. 天气报告发布时间(本地+异地)
    report_utc = datetime.datetime.utcfromtimestamp(owm_api_data['dt'])
    local_tz_offset = datetime.timedelta(seconds=time.localtime().tm_gmtoff)
    report_local_time = (report_utc + local_tz_offset).strftime("%Y-%m-%d %H:%M")
    report_remote_time = (report_utc + remote_timezone_offset).strftime("%Y-%m-%d %H:%M")
    
    # 5. 3小时预报列表
    three_hour_forecasts = []
    for forecast_item in owm_api_data['list']:
        forecast_utc = datetime.datetime.utcfromtimestamp(forecast_item['dt'])
        forecast_remote_time = (forecast_utc + remote_timezone_offset).strftime("%Y-%m-%d %H:%M")
        three_hour_forecasts.append({
            "forecast_time": forecast_remote_time,
            "weather_desc": forecast_item['weather'][0]['description'],
            "temperature": forecast_item['main']['temp']
        })
    
    # 返回结构化结果
    return {
        "local_time": local_time,
        "remote_local_time": remote_local_time,
        "remote_sunrise_time": remote_sunrise,
        "remote_sunset_time": remote_sunset,
        "report_publish_time_local": report_local_time,
        "report_publish_time_remote": report_remote_time,
        "three_hour_forecasts": three_hour_forecasts
    }

注意事项

  • 确认utc_offset的单位:Google Places返回的是秒,如果是其他API可能用小时,转换时要注意单位统一
  • 时区异常处理:如果遇到夏令时地区,Google Places的utc_offset已经包含了夏令时调整,直接用即可
  • 格式输出:可以根据需求调整时间的格式化字符串(比如strftime的参数),适配前端展示需求

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 03:42:59