Ross Watson Ross Watson - 4 months ago 13
Python Question

Python 2: print out the consecutive days in a loop

I have a script that prints out weather information. At the bottom of the script it is meant to print out the next eight days weather summary which it does. however I don't know how to print out consecutive days so the days match the description.

import sys
import os
import time
import optparse
import json
import urllib2

# You'll need an API key below... you get 1000 requests per day for free.

API="APIKEY"
URL="https://api.forecast.io/forecast/"

# Your latitude and longitude belong here, I use SF for example
LAT= 51.752725
LNG= -0.339436

#Direction of the wind
directions = ["N", "NE", "E", "SE", "S", "SW", "W", "NW"]

def bearing_to_direction(bearing):
d = 360. / 8.
return directions[int((bearing+d/2)/d)]

now = time.time()

req = urllib2.Request(URL+API+"/"+("%f,%f"%(LAT,LNG))+"?units=uk2")
response = urllib2.urlopen(req)
parsed = json.loads(response.read())
f = open("WEATHER.cache", "w")
f.write(json.dumps(parsed, indent=4, sort_keys=True))
f.close() ;

c = parsed["currently"]
print ":::", time.strftime("%H:%M", time.localtime(c["time"]))
print ":::", time.strftime("%A, %d %B %Y\n")
print "::: Conditions:", c["summary"]
print "::: Temperature:", ("%.1f" % c["temperature"])+u"\u00B0C"
print "::: Humidity:", ("%4.1f%%" % (c["humidity"]*100.))
print "::: Wind:", int(round(c["windSpeed"])), "mph", bearing_to_direction(c["windBearing"])

d = parsed["daily"]["data"][0]
print "::: High:", ("%.1f" % d["temperatureMax"])+u"\u00B0C"
print "::: Low:", ("%.1f" % d["temperatureMin"])+u"\u00B0C"

d = parsed["daily"]["data"]

for x in d[1:8]:
print time.strftime("\t%A:"), ("%.1f" % x["temperatureMax"])+u"\u00B0C -", x["summary"]


Every works in the code apart from this section:

for x in d[1:8]:
print time.strftime("\t%A:"), ("%.1f" % x["temperatureMax"])+u"\u00B0C -", x["summary"]


At the moment it just prints Thursday with all the eight days description beside it.

::: Low: 13.0°C
Thursday Partly cloudy throughout the day.
Thursday Partly cloudy throughout the day.
Thursday Light rain starting in the afternoon.
Thursday Light rain until afternoon.
Thursday Drizzle starting in the afternoon, continuing until evening.
Thursday Light rain until evening.
Thursday Light rain starting in the afternoon, continuing until evening.
Thursday Light rain starting in the evening.

Answer

Modify your time (not a good idea using this as a name) into a datetime instance, instead of time instance, and then you can use datetime.timedelta to increment the datetime object:

from datetime import timedelta, datetime

t = datetime.now()
for i, x in enumerate(d[:12]):
    print (t+timedelta(days=i)).strftime("\t%A:"), x["summary"]