2016-07-07 2 views
0

У меня есть сценарий, который печатает информацию о погоде. В нижней части сценария он предназначен для печати следующего восьмидневного сводка погоды, который он делает. однако я не знаю, как распечатать последовательные дни, чтобы дни соответствовали описанию.Python 2: распечатать последовательные дни в цикле

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"] 

Каждый работает в коде помимо этого раздела:

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

На данный момент он просто печатает в четверг со всем описанием восемь дней рядом с ним.

::: 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. 
+0

Это даже не приближается к достаточному коду. Откуда «время»? Вам действительно нужно прочитать [mcve]. –

ответ

3

Изменить ваш time (не очень хорошая идея использовать это в качестве имени) в datetime Например, вместо time инстанции, а затем вы можете использовать datetime.timedelta для увеличения datetime объекта:

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"] 
Смежные вопросы