For循环使用Python - 使用in而不是datetime

时间:2015-05-15 07:35:25

标签: python for-loop

我有一项数据科学任务,需要获取历史天气数据。我查看了wunderground.com,但他们的API示例结构如下:

http://api.wunderground.com/api/d23ac65706dbf6dd/history_YYYYMMDD/q/CA/San_Francisco.json

因此,在尝试构建数据集时,我需要从一年的第一天到一年的最后一天,但不能这样做:

    20140101
    20140102
    20140103
    ...
    20141229
    20141230
    20141231

我唯一能想到的是:

for m in range(1, 13):
    for d in range(1, 32):
         r = requests.get("http://api.wunderground.com/api/0def10027afaebb7/history_2014'+str(m)+'/'+str(d)+'/q/Mexico/Mexico_City.json")
        data = r.json()

但这显然不会奏效。你会如何在Python中解决这个问题?

3 个答案:

答案 0 :(得分:6)

这是一个演示如何迭代实际日期的最小示例:

>>> import datetime
>>> start = datetime.date(2014, 1, 1)
>>> end = datetime.date(2014, 1, 5)
>>> while start <= end:
    print start.strftime('%Y%m%d')
    start += datetime.timedelta(days=1)


20140101
20140102
20140103
20140104
20140105

有关详细信息,请参阅the datetime documentation

答案 1 :(得分:1)

使用calendar模块的替代方案:

>>> import calendar
>>> cal = calendar.Calendar()
>>> year = 2014
>>> for month in range(1,13):
...    for day in cal.itermonthdates(year, month):
...        if day.year == year:
...           print day.strftime('%Y%m%d')
... 
20140101
20140102
20140103
20140104
...
...
20141229
20141230
20141231

答案 2 :(得分:0)

相反,您可以使用datetime将int转换为datetime格式,并检查年份是否符合您的要求。 例如

import datetime
s = 20140101
s_datetime = datetime.datetime.strptime(str(s), '%Y%m%d')
if s_datetime.year == 2014:
    //Do something