はじめに
近頃気候の変化で体調が影響受けていることが多い気がして、過去の気候情報を確認したかったが、
有料プランなどでないとなかなか過去の気候の実績情報がなかったため集積ツールを自作して日々集積してみることにした。
本記事の内容は、OpenWeatherMapAPIを利用して気候情報を取得する方法になります。
概要
本ツールは、Pythonを用いてOpenWeatherMapAPIから以下の情報を取得し、Excelファイルに記録するツール。
- 日付
- 時間
- 温度
- 湿度
- 風速
- 気圧
- 天気
手順
アカウント作成
アカウント作成については、以下の記事を参考にさせていただきました。
無料天気予報APIのOpenWeatherMapを使ってみる
アカウントを作成すると、デフォルトのAPIキーが払い出される。
キーの追加も可能だが、アクティベートには時間がかかる。
実装
import requests
import pandas as pd
from openpyxl import Workbook, load_workbook
from datetime import datetime
import os
# OpenWeatherMap API
API_KEY = "" # APIキーを設定
LAT = # 地点情報(緯度)
LON = # 地点情報(経度)
WEATHER_URL = f"https://api.openweathermap.org/data/2.5/weather?lat={LAT}&lon={LON}&appid={API_KEY}&units=metric"
# Excel 出力パスを指定
output_dir = r""
os.makedirs(output_dir, exist_ok=True)
excel_file = os.path.join(output_dir, "weather_data.xlsx") # ファイル名
def fetch_weather():
"""OpenWeatherMap API から現在の天気データを取得"""
response = requests.get(WEATHER_URL)
if response.status_code == 200:
data = response.json()
temp = data["main"]["temp"] # 温度
humidity = data["main"]["humidity"] # 湿度
wind_speed = data["wind"]["speed"] # 風速
pressure = data["main"]["pressure"] # 気圧
weather_description = data["weather"][0]["description"] # 天気
timestamp = datetime.now()
return timestamp, temp, humidity, wind_speed, pressure, weather_description
else:
print("APIエラー:", response.status_code)
print("詳細:", response.text)
return None
def save_weather_data():
"""天気データを取得してExcelに記録"""
weather_data = fetch_weather()
if weather_data is None:
return
timestamp, temp, humidity, wind_speed, pressure, weather_description = weather_data
month_str = timestamp.strftime("%Y-%m") # シート名 (例:2025-04)
date_str = timestamp.strftime("%Y-%m-%d") # 日付 (例:2025-04-02)
time_str = timestamp.strftime("%H:%M") # 時間 (例:14:00)
try:
wb = load_workbook(excel_file) # 既存ファイルを開く
except FileNotFoundError:
wb = Workbook() # ファイルがない場合は新規作成
if month_str not in wb.sheetnames:
ws = wb.create_sheet(title=month_str)
ws.append(["日付", "時間", "温度 (°C)", "湿度 (%)", "風速 (m/s)", "気圧 (hPa)", "天気"])
else:
ws = wb[month_str]
ws.append([date_str, time_str, temp, humidity, wind_speed, pressure, weather_description])
wb.save(excel_file)
print(f"データ保存: {month_str} {date_str} {time_str} -> {temp}°C, {humidity}%, {wind_speed}m/s, {pressure}hPa, {weather_description}")
# 天気データ取得&保存
save_weather_data()
実装のポイント
- APIキー、観測地点情報、出力ファイル名を適宜設定。
- データは月ごとにシートで管理。
- 定時実行には、Windowsのタスクスケジューラなどのバッチツールを利用。
終わりに
ECSなどのサーバを利用すれば問題ないが、ローカル環境では常時ネット接続が必要となる。
Excel管理ではなくデータベースを使用して、日々の体調情報も記録できるアプリ形式に拡張すればもっと便利になると考えられる。
OpenWeatherMapAPIや気候情報APIは活用の幅が広く、さまざまな用途で応用できると感じたため、今後も活用していきたい。