Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/python3
- import json
- import urllib.request
- import time
- from calendar import timegm
- import platform
- if platform.uname().machine[0:6] == "iPhone":
- import console
- console.clear()
- def add_next(n, l):
- if len(l) < n:
- return None
- if n < 1:
- return (0, 0)
- return (l[0][0] + add_next(n - 1, l[1:])[0], l[0][1])
- url = 'https://api.octopus.energy/v1/products/AGILE-18-02-21/electricity-tariffs/E-1R-AGILE-18-02-21-A/standard-unit-rates/'
- try:
- with urllib.request.urlopen(url, timeout=30) as u:
- data = u.read()
- except:
- print("Couldn't read data from {}.".format(url))
- exit()
- try:
- decoded_data = json.loads(data.decode('utf-8'))
- except:
- print("Webserver didn't return valid JSON")
- exit()
- now = time.time()
- prices = [(x['value_inc_vat'], timegm(time.strptime(x['valid_from'],
- '%Y-%m-%dT%H:%M:%SZ')))
- for x in decoded_data['results']]
- future_prices = [x for x in prices if x[1] > now]
- future_prices.sort(key=lambda x: x[1])
- three_hour_prices = []
- for x in range(len(future_prices)):
- thp = add_next(6, future_prices[x:])
- if thp is not None:
- three_hour_prices.append((round(thp[0] / 6, 2), thp[1]))
- three_hour_prices.sort(key=lambda x: x[0])
- avg_price, start_time = (three_hour_prices[0][0],
- time.localtime(three_hour_prices[0][1]))
- print(f"Cheapest 3 hours starts at {start_time.tm_hour:02}:{start_time.tm_min:02}\nwith an average price of {avg_price} pence per kilowatt hour.")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement