调用API历史和未来气象数据获取
·
在做业务中需要用到气象数据,这就需要自己去找,推进一个API,调用接口,输出经纬度就可以获取历史及未来相关气象维度的数据了。
历史气象数据获取
import openmeteo_requests
from datetime import datetime,timedelta
import pandas as pd
import time
import requests_cache
from retry_requests import retry
#输入地区的经纬度
longitude = '122.32'
latitude = '23.42'
cache_session = requests_cache.CachedSession('.cache', expire_after = -1)
retry_session = retry(cache_session, retries = 5, backoff_factor = 0.2)
openmeteo = openmeteo_requests.Client(session = retry_session)
url = "https://archive-api.open-meteo.com/v1/archive"
start_tday = pd.to_datetime(datetime.now().strftime('%Y-%m-%d'))
end_tday = (start_tday-timedelta(days = 1)).strftime('%Y-%m-%d')
params = {
"latitude": latitude,
"longitude": longitude,
"start_date": "2025-07-14",
"end_date": end_tday,
"daily": ["temperature_2m_max", "temperature_2m_min", "apparent_temperature_max", "apparent_temperature_min", "wind_speed_10m_max", "sunshine_duration", "apparent_temperature_mean", "temperature_2m_mean", "precipitation_sum", "et0_fao_evapotranspiration", "weather_code"],
"timezone": "auto"
}
responses = openmeteo.weather_api(url, params=params)
# Process first location. Add a for-loop for multiple locations or weather models
response = responses[0]
print(f"Coordinates {response.Latitude()}°N {response.Longitude()}°E")
print(f"Elevation {response.Elevation()} m asl")
print(f"Timezone {response.Timezone()}{response.TimezoneAbbreviation()}")
print(f"Timezone difference to GMT+0 {response.UtcOffsetSeconds()} s")
# Process daily data. The order of variables needs to be the same as requested.
daily = response.Daily()
temperature_2m_max = daily.Variables(0).ValuesAsNumpy()
temperature_2m_min = daily.Variables(1).ValuesAsNumpy()
apparent_temperature_max = daily.Variables(2).ValuesAsNumpy()
apparent_temperature_min = daily.Variables(3).ValuesAsNumpy()
wind_speed_10m_max = daily.Variables(4).ValuesAsNumpy()
sunshine_duration = daily.Variables(5).ValuesAsNumpy()
apparent_temperature_mean = daily.Variables(6).ValuesAsNumpy()
temperature_2m_mean = daily.Variables(7).ValuesAsNumpy()
precipitation_sum = daily.Variables(8).ValuesAsNumpy()
et0_fao_evapotranspiration = daily.Variables(9).ValuesAsNumpy()
weather_code= daily.Variables(10).ValuesAsNumpy()
weather_data = pd.DataFrame({
'时间': pd.date_range(start='2025-07-14', end=end_tday)
,'最高温度':temperature_2m_max
,'最低温度':temperature_2m_min
,'最高表观温度':apparent_temperature_max
,'最低表观温度':apparent_temperature_min
,'最大风速':wind_speed_10m_max
,'日照持续时间':sunshine_duration
,'平均表观温度':apparent_temperature_mean
,'平均温度':temperature_2m_mean
,'降雨总和':precipitation_sum
,'参考蒸散量':et0_fao_evapotranspiration
,'天气代码':weather_code})
time.sleep(2)

未来气象数据获取
未来气象最多能获取16天的。
import openmeteo_requests
from datetime import datetime,timedelta
import pandas as pd
import time
import requests_cache
from retry_requests import retry
longitude = '105.32'
latitude = '32.13'
# Setup the Open-Meteo API client with cache and retry on error
cache_session = requests_cache.CachedSession('.cache', expire_after = 3600)
retry_session = retry(cache_session, retries = 5, backoff_factor = 0.2)
openmeteo = openmeteo_requests.Client(session = retry_session)
# Make sure all required weather variables are listed here
# The order of variables in hourly or daily is important to assign them correctly below
url = "https://api.open-meteo.com/v1/forecast"
forecast_days = 16
params = {
"latitude": latitude,
"longitude": longitude,
"daily": ["temperature_2m_max", "temperature_2m_min", "apparent_temperature_max", "apparent_temperature_min", "wind_speed_10m_max", "sunshine_duration", "apparent_temperature_mean", "temperature_2m_mean", "precipitation_sum", "et0_fao_evapotranspiration", "weather_code"],
"timezone": "auto",
"forecast_days": forecast_days
}
responses = openmeteo.weather_api(url, params=params)
response = responses[0]
print(f"Coordinates {response.Latitude()}°N {response.Longitude()}°E")
print(f"Elevation {response.Elevation()} m asl")
print(f"Timezone {response.Timezone()}{response.TimezoneAbbreviation()}")
print(f"Timezone difference to GMT+0 {response.UtcOffsetSeconds()} s")
# Process daily data. The order of variables needs to be the same as requested.
daily = response.Daily()
temperature_2m_max = daily.Variables(0).ValuesAsNumpy()
temperature_2m_min = daily.Variables(1).ValuesAsNumpy()
apparent_temperature_max = daily.Variables(2).ValuesAsNumpy()
apparent_temperature_min = daily.Variables(3).ValuesAsNumpy()
wind_speed_10m_max = daily.Variables(4).ValuesAsNumpy()
sunshine_duration = daily.Variables(5).ValuesAsNumpy()
apparent_temperature_mean = daily.Variables(6).ValuesAsNumpy()
temperature_2m_mean = daily.Variables(7).ValuesAsNumpy()
precipitation_sum = daily.Variables(8).ValuesAsNumpy()
et0_fao_evapotranspiration = daily.Variables(9).ValuesAsNumpy()
weather_code= daily.Variables(10).ValuesAsNumpy()
start_tday = pd.to_datetime(datetime.now().strftime('%Y-%m-%d'))
end_tday = start_tday+timedelta(days = int(forecast_days-1))
Fweather_data = pd.DataFrame({
'时间': pd.date_range(start=start_tday, end=end_tday)
,'最高温度':temperature_2m_max
,'最低温度':temperature_2m_min
,'最高表观温度':apparent_temperature_max
,'最低表观温度':apparent_temperature_min
,'最大风速':wind_speed_10m_max
,'日照持续时间':sunshine_duration
,'平均表观温度':apparent_temperature_mean
,'平均温度':temperature_2m_mean
,'降雨总和':precipitation_sum
,'参考蒸散量':et0_fao_evapotranspiration
,'天气代码':weather_code})
time.sleep(2)

DAMO开发者矩阵,由阿里巴巴达摩院和中国互联网协会联合发起,致力于探讨最前沿的技术趋势与应用成果,搭建高质量的交流与分享平台,推动技术创新与产业应用链接,围绕“人工智能与新型计算”构建开放共享的开发者生态。
更多推荐



所有评论(0)