#!/usr/bin/python3
# ===================================================================
# access NWS weather forecast data
# ===================================================================
# thanks to: https://benborgers.com/posts/weather-gov
# How to use the weather.gov API
# note: This is where I finally figured out how to access the
# weather data
# ===================================================================
from datetime import datetime
import requests
import json
# ---- weather forcase location (lat/lon)
lat = '34.149551' # Pasadena, CA
lon = '-118.141449' # Pasadena, CA
# ---- get weather data for lat/lon (JSON object)
url = f'https://api.weather.gov/points/{lat},{lon}'
r = requests.get(url)
j_obj = r.json()
# ---- get forecast data for lat/lon
url = j_obj['properties']['forecast']
r = requests.get(url)
j_obj = r.json()
f = j_obj['properties']['periods']
# ---- display 7 day forecast
now = datetime.now()
dt = now.strftime('%d/%m/%Y %H:%M:%S')
title = f'# 7 day forecast on {dt}'
print()
print(title)
print()
for i in range(len(f)):
p = f[i]
str = f'[{p["number"]:2}] ' + \
f'{p["name"]:16} ' + \
f'{p["temperature"]:3} deg-{p["temperatureUnit"]}'
print(str)
# ---- write forecaste as CSV file
# ---- --------------------------------------------------------------
# ---- Note: print(str,file=file) and file.write(str + '\n')
# ---- are basicaly the same; pick one; (see example below)
# -------------------------------------------------------------------
outfile = 'forecast.csv'
with open(outfile,'w') as file:
print(title,file=file)
for i in range(len(f)):
p = f[i]
str = f'{p["number"]},' + \
f'{p["name"]},' + \
f'{p["temperature"]},{p["temperatureUnit"]}'
file.write(str + '\n')
print()