Python 3 个日历

Python 3 Calendar

谁知道如何从日历函数中制作 Python return 这样的日期格式?:

date = "20170714"

基本上,如果 API 收集每小时天气数据的请求可能的话,我正在寻找一些增强功能。我的问题是每天都需要重新 运行 代码。重新运行脚本 365 次以获取一年的天气数据有点笨拙且耗时,但这是我知道的唯一方法。带有日历功能的循环可以自动执行操作吗?

from urllib.request import urlopen
from pandas.io.json import json_normalize
import json
import pandas as pd

api_key = ""
date = "20170714"
zip_code = "96345"

response = urlopen("http://api.wunderground.com/api/%s/history_%s/q/%s.json" % (api_key, date, zip_code))

json_data = response.read().decode('utf-8', 'replace')

data = json.loads(json_data)

for observation in data['history']['observations']:
     print("Date/Time:    " + observation['date']['pretty'])
     print("Temperature:  " + observation['tempi'])
     print("Humidity:     " + observation['hum'])

df = json_normalize(data['history']['observations'])

df = df[['date.pretty','tempi','hum']]
df['date.pretty'] = pd.to_datetime(df['date.pretty'])

print(df)

这个简单的日历脚本可以 return 2013 年 12 月的每一天,但它不是地下天气 API 可以理解的格式...最终我希望创建一个API 请求可以使用日历功能收集一个月数据(一次甚至一整年)的循环与一天手动时尚....这可能吗??!

import calendar

tc = calendar.TextCalendar(firstweekday=0)

for i in tc.itermonthdays(2013,12):
    print(i)

谢谢

非常pythonic,但是因为你只需要一次我认为这没问题,这里是我使用的代码:

import calendar

datelst = []
year = 2013
for month in range(1,13):
    days = range(1,calendar.monthrange(year,month)[1]+1)
    if month<10:
        for day in days:
            if day<10:
                datelst.append(str(year)+'0'+str(month)+'0'+str(day))
            else:
                datelst.append(str(year)+'0'+str(month)+str(day))
    else:
        for day in days:
            if day<10:
                datelst.append(str(year)+str(month)+'0'+str(day))
            else:
                datelst.append(str(year)+str(month)+str(day))

现在 datelst 以您想要的方式包含 2013 年的所有日期,因此 2013 年的第 i 天现在是:datelst[i-1]。使用 for 循环遍历所有天数。

使用免费 API 密钥一天可以发出多少请求是有限制的,但这是我建议的方式。请注意,任何与日期 and/or 时间相关的内容我几乎总是使用箭头包。这些方面的内容应该适合您。

import arrow # learn more: https://python.org/pypi/arrow
from WunderWeather import weather # learn more: https://python.org/pypi/WunderWeather

api_key = ''
extractor = weather.Extract(api_key)
zip = '96345'

# get 20170101 00:00
begin_date = arrow.get("2017","YYYY")
# get 20171231 23:00
end_date = arrow.get("2018","YYYY").shift(hours=-1)
for date in arrow.Arrow.range('hour',begin_date,end_date):
  # get date object for feature
  # http://wunderweather.readthedocs.io/en/latest/WunderWeather.html#WunderWeather.weather.Extract.date
  date_weather = extractor.date(zip,date.format('YYYYMMDD'))

  # use shortcut to get observations and data
  # http://wunderweather.readthedocs.io/en/latest/WunderWeather.html#WunderWeather.date.Observation
  for observation in date_weather.observations:
    print("Date:",observation.date_pretty)
    print("Temp:",observation.temp_f)