Python根据日期范围每天保存JSON响应

时间:2019-03-05 12:27:16

标签: python json date

例如,我们有日期范围(START = 2019-01-01,END = 2019-03-01)

然后我们有2个功能:

1)一个执行某些操作并保存对文件的响应的过程:

def job_function():
     # Date are part of parameters like this:
        dates.gt({}).lt({})'.format(START,END),
     # Here should be the code which ends up with :
        responseMain = requests.get(urlMain, params=params, headers=headers).json()
        with open(FILE_NAME, "a+") as outfile:
             outfile.write(json.dumps(responseMain))

2)主要一:

if __name__ == '__main__':

  for (something here? or something inside the function 1??) 
     sm_data(START,END)

我需要修改功能1,它将采用主要日期范围,并且每天都会通过处理连续运行。

E.G。 IF日期范围是(START = 2019-01-01,END = 2019-03-01)

功能1将从该日期开始连续运行:

  • START = 2019-01-01,END = 2019-01-02
  • START = 2019-01-02,END = 2019-01-03
  • START = 2019-01-03,END = 2019-01-04
  • START = 2019-01-04,END = 2019-01-05
  • START = 2019-01-05,END = 2019-01-06
  • START = 2019-01-06,END = 2019-01-07
  • START = 2019-01-07,END = 2019-01-08
  • START = 2019-01-08,END = 2019-01-09

直到-START = 2019-02-28,END = 2019-03-01

在处理过程中,数据将追加到同一文件

编辑1:这是一种变通方法,可以在时间范围内每天提取数据,而不是在整个日期范围内求和

1 个答案:

答案 0 :(得分:1)

我在这里假设您的代码包含一个存在两个变量的地方: START = 2019-01-01和END = 2019-03-01。

您只需保存它们并编写一个循环,为每次迭代设置它们并调用sm_data

# ok START and END exist here
# convert them to datetime.date
fmt = '%Y-%m-%d'
cur = datetime.datetime.strptime(START, fmt).date()
end = datetime.datetime.strptime(END, fmt).date()
# prepare the loop:
delta = datetime.timedelta(days=1)
while cur < end:
    START = cur.strftime(fmt)      # current date
    cur += delta                   # next day
    END = cur.strftime(fmt)
    sm_data(START, END)