Home > OS >  Stop Python date iteration before current month
Stop Python date iteration before current month

Time:07-15

The following is meant to iterate through months and pointID to create an API link, my goal is to export this to a JSON file. How would I go about stopping the loop at the current month? as it stands it produces a link for August 2022 which stops the script as there is no data .

import calendar
import requests
import json

pointId = ['9804', '9805']  

def get_datas(year):
    for point in pointId:
        for month in range(1, 13):
            r = calendar.monthrange(year, month)
            start = f"{year}-{month:0>2d}-01"
            end = f"{year}-{month:0>2d}-{r[1]}"

            url = f"https://live.api/raw?pointID={point}&startDateUTC={start}&endDateUTC={end}&interval=mm&summed=1&productTypeID=2"

            print(url)

            payload={}
            headers = {
            'Authorization': 'Bearer abcdefg1234556'
            }

            response = requests.request("GET", url, headers=headers, data=payload)

            data = json.loads(response.text)
            yield data

datas = []
for year in (2020, 2021, 2022):
    datas.extend(get_datas(year))

with open('PS_Consumption.json', 'w') as json_file:
    json.dump(datas, json_file, indent=4)

CodePudding user response:

You can check if current_year == now.year and current_month == now.month and if this is the case, stop the loop with break.

import requests
import calendar
from datetime import datetime


def get_data(year):
    result = []
    for point_id in point_ids:
        for month in range(1, 13):
            now = datetime.now()
            if now.year == year and now.month == month: break

            r = calendar.monthrange(year, month)
            [start, end] = [f'{year}-{month:0>2d}-01', f'{year}-{month:0>2d}-{r[1]}']
            url = f'https://live.api/raw?pointID={point_id}&startDateUTC={start}&endDateUTC={end}&interval=mm&summed=1&productTypeID=2'

            headers = {'Authorization': 'Bearer abcdefg1234556'}
            response = requests.get(url, headers=headers, data={})
            
            data = json.loads(response.text)
            result.append(data)

    return result
            

point_ids = ['9804', '9805']

data = []
for year in (2020, 2021, 2022): data.extend(get_data(year))
  • Related