Skip to content

Commit

Permalink
Should work better pre pytz
Browse files Browse the repository at this point in the history
  • Loading branch information
grigsos committed Apr 15, 2023
1 parent 741a9ca commit d9751b6
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 6 deletions.
5 changes: 3 additions & 2 deletions dynamodb_func.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,8 +41,10 @@ def put_data_to_dynamodb(responseAPI: Dict[str, Any]) -> Dict[str, Any]:
last_timestamp : datetime.datetime = lTimestampsResponse[-1]



if str(last_timestamp) != str(datetime.strptime(param['lastUpdated'], '%Y-%m-%dT%H:%M:%S%z')): # need to update
lTimestampsResponse.append(last_timestamp)
print("added")
lTimestampsResponse.append(datetime.strptime(param['lastUpdated'], '%Y-%m-%dT%H:%M:%S%z'))
last_reading : float = float(param['lastValue'])
lReadingsResponse.append(last_reading)
up_av,up_lt,up_lr = calculate_weighted_average(lReadingsResponse,lTimestampsResponse)
Expand All @@ -51,7 +53,6 @@ def put_data_to_dynamodb(responseAPI: Dict[str, Any]) -> Dict[str, Any]:
write_requests.append({'DeleteRequest': {'Key': key}})
else:
up_ltISO = convert_datetime_to_iso(up_lt)

item = {
PARTITION_KEY: {'N': str(param['id'])},
'name_provider' :response['Item']['name_provider'],
Expand Down
16 changes: 12 additions & 4 deletions utils.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from datetime import datetime, timedelta
from typing import Any, Dict, List, Optional, Union, Tuple
import pytz

from constants import HOURS_THRESHOLD

Expand All @@ -26,25 +27,32 @@ def calculate_weighted_average(readings: List[float], timestamps: List[datetime]
else:
total_weight = 0
weighted_sum = 0

print(recent_datetimes)

# Calculate the weighted average over the past x hours
for i in range(len(recent_datetimes)-1, -1, -1):
time_diff = datetime.now() - recent_datetimes[i]
tz = pytz.timezone('UTC') # create a timezone object with UTC offset
recent_datetime_with_tz = tz.localize(recent_datetimes[i]) # add timezone information to datetime object
time_diff = datetime.datetime.now(datetime.timezone.utc) - recent_datetime_with_tz

weight = 1 / time_diff.total_seconds() # Use inverse time difference as weight
total_weight += weight
weighted_sum += weight * recent_readings[i]

try:
avg = weighted_sum / total_weight
except ZeroDivisionError:
avg = 0



return round(avg, 3), recent_datetimes, recent_readings



def get_recent_datetimes(datetime_list: List[datetime], readings_list: List[float]) -> Tuple[List[datetime], List[float]]:

print(datetime_list)
print(readings_list)
now = datetime.now()
recent_datetimes = []
recent_readings = []
Expand Down

0 comments on commit d9751b6

Please sign in to comment.