Advertisement
Guest User

dishwasher.py

a guest
Feb 21st, 2020
191
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.58 KB | None | 0 0
  1. #!/usr/bin/python3
  2.  
  3. import json
  4. import urllib.request
  5. import time
  6. from calendar import timegm
  7.  
  8. import platform
  9. if platform.uname().machine[0:6] == "iPhone":
  10.     import console
  11.     console.clear()
  12.  
  13.  
  14. def add_next(n, l):
  15.     if len(l) < n:
  16.         return None
  17.     if n < 1:
  18.         return (0, 0)
  19.     return (l[0][0] + add_next(n - 1, l[1:])[0], l[0][1])
  20.  
  21.  
  22. url = 'https://api.octopus.energy/v1/products/AGILE-18-02-21/electricity-tariffs/E-1R-AGILE-18-02-21-A/standard-unit-rates/'
  23.    
  24. try:
  25.     with urllib.request.urlopen(url, timeout=30) as u:
  26.         data = u.read()
  27. except:
  28.     print("Couldn't read data from {}.".format(url))
  29.     exit()
  30.  
  31. try:
  32.     decoded_data = json.loads(data.decode('utf-8'))
  33. except:
  34.     print("Webserver didn't return valid JSON")
  35.     exit()
  36.  
  37. now = time.time()
  38. prices = [(x['value_inc_vat'], timegm(time.strptime(x['valid_from'],
  39.                                                      '%Y-%m-%dT%H:%M:%SZ')))
  40.           for x in decoded_data['results']]
  41. future_prices = [x for x in prices if x[1] > now]
  42.  
  43. future_prices.sort(key=lambda x: x[1])
  44.  
  45. three_hour_prices = []
  46. for x in range(len(future_prices)):
  47.     thp = add_next(6, future_prices[x:])
  48.     if thp is not None:
  49.         three_hour_prices.append((round(thp[0] / 6, 2), thp[1]))
  50.  
  51. three_hour_prices.sort(key=lambda x: x[0])
  52.  
  53. avg_price, start_time = (three_hour_prices[0][0],
  54.                          time.localtime(three_hour_prices[0][1]))
  55. 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