Python 2:在循环中打印出连续几天

时间:2016-07-07 13:49:37

标签: python python-2.7 time

我有一个打印出天气信息的脚本。在脚本的底部,它打算打印出它接下来的八天天气摘要。但我不知道如何打印连续几天所以天数符合描述。

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.

1 个答案:

答案 0 :(得分: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"]