Skip to content

Commit 0bcd48c

Browse files
authored
Merge pull request #6 from doingmathwithpython/amitsaha-patch-2
Chapter 2: temp forecast using pyowm
2 parents d172ee1 + 3d5f03c commit 0bcd48c

File tree

1 file changed

+25
-10
lines changed

1 file changed

+25
-10
lines changed

chapter2/solutions/nyc_forecast_owm.py

Lines changed: 25 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,39 @@
11
'''
2-
Retrieve a day's forecast of New York City and create a graph
2+
Retrieve three days' forecast of New York City and create a graph
33
Using https://github.com/csparpa/pyowm
44
'''
55
import matplotlib.pyplot as plt
66
from pyowm import OWM
7+
import pytz
78

8-
owm = OWM()
9+
owm = OWM('<token>')
910

1011
def get_forecast(city):
11-
fc = owm.daily_forecast(city, limit=1)
12+
# https://github.com/csparpa/pyowm/issues/266
13+
fc = owm.three_hours_forecast(city)
1214
f = fc.get_forecast()
13-
w = f.get_weathers()[0]
14-
forecast_temp = w.get_temperature('celsius')
15-
day_intervals = ['morn', 'day', 'eve', 'night']
15+
16+
# three_hours_forecast() returns 5 day forecast at a granularity
17+
# of three hours
18+
# we plot them all
19+
weathers = f.get_weathers()
20+
21+
22+
data_points = ['temp', 'temp_max', 'temp_min', 'temp_kf']
1623
temp = []
17-
for timeofday in day_intervals:
18-
temp.append(forecast_temp[point])
19-
x = range(1, len(day_intervals)+1)
24+
date_time = []
25+
for w in weathers:
26+
forecast_temp = w.get_temperature('celsius')
27+
utc_dt = datetime.utcfromtimestamp(w.get_reference_time()).replace(tzinfo=pytz.utc)
28+
tz = pytz.timezone('America/New_York')
29+
dt = utc_dt.astimezone(tz)
30+
31+
# print it
32+
date_time.append(dt.strftime('%Y-%m-%d %H:%M:%S %Z%z'))
33+
temp.append(forecast_temp['temp'])
34+
x = range(1, len(temp)+1)
2035
plt.plot(x, temp, 'o-')
21-
plt.xticks(x, day_intervals)
36+
plt.xticks(x, date_time)
2237
plt.show()
2338

2439
if __name__ == '__main__':

0 commit comments

Comments
 (0)