Skip to content

Commit ef37351

Browse files
committed
Implement TimeHandler.get_time() and TimeHandler.get_date_as_string()
1 parent 5e60445 commit ef37351

8 files changed

+28
-28
lines changed

source/abscence_handler.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,7 @@ def _check_for_current_absence(self, absence_input: str) -> bool:
4040
if timestamp.tzinfo is None:
4141
raise ValueError(f'"{absence_start_raw}" has no timezone information')
4242

43-
if absence_start < datetime.now(tz=TimeHandler.get_timezone()) < absence_end:
43+
if absence_start < TimeHandler.get_time() < absence_end:
4444
return True
4545

4646
return False

source/deprecated_sun_forecast_handler.py

+2-10
Original file line numberDiff line numberDiff line change
@@ -14,14 +14,6 @@ class DeprecatedSunForecastHandler(LoggerMixin):
1414
def __init__(self):
1515
super().__init__()
1616

17-
@staticmethod
18-
def _get_date_as_string() -> str:
19-
"""
20-
Returns:
21-
str: The current date formatted as 'YYYY-MM-DD'.
22-
"""
23-
return datetime.datetime.now().strftime("%Y-%m-%d")
24-
2517
def get_expected_solar_output_of_today(self) -> EnergyAmount:
2618
"""
2719
Gets the expected solar energy output for the current day.
@@ -55,7 +47,7 @@ def get_expected_solar_output_of_today(self) -> EnergyAmount:
5547
data = response.json()
5648
self.log.trace(f"Retrieved data: {data}")
5749

58-
total_solar_forecast += data["result"][self._get_date_as_string()]
50+
total_solar_forecast += data["result"][TimeHandler.get_date_as_string()]
5951

6052
return total_solar_forecast
6153

@@ -130,7 +122,7 @@ def _get_sunset_and_sunrise_with_offset(self) -> tuple[datetime, datetime]:
130122
Returns:
131123
tuple[datetime, datetime]: A tuple containing the adjusted sunrise and sunset times.
132124
"""
133-
date = datetime.datetime.now()
125+
date = TimeHandler.get_time()
134126
sun = SunTimes(
135127
float(EnvironmentVariableGetter.get("LOCATION_LONGITUDE")),
136128
float(EnvironmentVariableGetter.get("LOCATION_LATITUDE")),

source/inverter_charge_controller.py

+4-6
Original file line numberDiff line numberDiff line change
@@ -54,9 +54,7 @@ def start(self) -> None:
5454
next_price_minimum, minimum_has_to_be_rechecked = self._do_iteration()
5555

5656
if minimum_has_to_be_rechecked:
57-
time_to_sleep_to = datetime.now(tz=self.timezone).replace(
58-
hour=14, minute=0, second=0, microsecond=0
59-
)
57+
time_to_sleep_to = TimeHandler.get_time().replace(hour=14, minute=0, second=0, microsecond=0)
6058
self.log.info(f"The price minimum has to re-checked at {time_to_sleep_to}. Waiting until then...")
6159
pause.until(time_to_sleep_to)
6260
self.log.info("Waking up since the the price minimum has to re-checked")
@@ -98,7 +96,7 @@ def _do_iteration(self) -> tuple[datetime, bool]: # FIXME: Find better name
9896
"Waiting is over, now is the a price minimum. Checking what has to be done to reach the next minimum..."
9997
)
10098

101-
timestamp_now = datetime.now(tz=self.timezone)
99+
timestamp_now = TimeHandler.get_time()
102100

103101
next_price_minimum, minimum_has_to_be_rechecked = self.tibber_api_handler.get_timestamp_of_next_price_minimum()
104102
self.log.info(f"The next price minimum is at {next_price_minimum}")
@@ -202,12 +200,12 @@ def _do_iteration(self) -> tuple[datetime, bool]: # FIXME: Find better name
202200
required_state_of_charge = max_target_soc
203201

204202
energy_bought_before_charging = self.sems_portal_api_handler.get_energy_buy()
205-
timestamp_starting_to_charge = datetime.now(tz=self.timezone)
203+
timestamp_starting_to_charge = TimeHandler.get_time()
206204
self.log.debug(f"The amount of energy bought before charging is {energy_bought_before_charging}")
207205

208206
self._charge_inverter(required_state_of_charge)
209207

210-
timestamp_ending_to_charge = datetime.now(tz=self.timezone)
208+
timestamp_ending_to_charge = TimeHandler.get_time()
211209

212210
duration_to_wait_for_semsportal_update = timedelta(minutes=10)
213211
self.log.info(

source/main.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import signal
22
import sys
3-
from datetime import datetime, timedelta
3+
from datetime import timedelta
44
from types import FrameType
55

66
from deprecated_sun_forecast_handler import DeprecatedSunForecastHandler
@@ -14,7 +14,7 @@ def log_solar_forecast(log_as_review: bool = False) -> None:
1414
sun_forecast_handler = SunForecastHandler()
1515
deprecated_sun_forecast_handler = DeprecatedSunForecastHandler()
1616

17-
now = datetime.now(tz=TimeHandler.get_timezone())
17+
now = TimeHandler.get_time()
1818
start = now.replace(hour=5, minute=0, second=0, microsecond=0)
1919
end = now.replace(hour=23, minute=0, second=0, microsecond=0)
2020
if log_as_review:

source/sems_portal_api_handler.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -93,7 +93,7 @@ def _retrieve_energy_consumption_data(self) -> dict:
9393
"id": EnvironmentVariableGetter.get("SEMSPORTAL_POWERSTATION_ID"),
9494
"range": 2,
9595
"chartIndexId": "8",
96-
"date": datetime.now().strftime("%Y-%m-%d"),
96+
"date": TimeHandler.get_date_as_string(),
9797
}
9898

9999
response = requests.post(url, headers=headers, json=payload, timeout=20)

source/sun_forecast_handler.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,7 @@ def _get_debug_solar_output(self) -> EnergyAmount:
4040
def get_solar_output_in_timeframe(self, timestamp_start: datetime, timestamp_end: datetime) -> EnergyAmount:
4141
solar_data = []
4242

43-
now = datetime.now(tz=(TimeHandler.get_timezone())).replace(second=0, microsecond=0) - timedelta(
43+
now = TimeHandler.get_time().replace(second=0, microsecond=0) - timedelta(
4444
seconds=1
4545
) # Account for execution times of the program
4646
if timestamp_start >= now or timestamp_end >= now:
@@ -78,7 +78,7 @@ def get_solar_output_in_timeframe(self, timestamp_start: datetime, timestamp_end
7878

7979
if __name__ == "__main__":
8080
new_solar_forecast_handler = SunForecastHandler()
81-
start = datetime.now(tz=TimeHandler.get_timezone()).replace(hour=0, minute=0, second=0, microsecond=0)
81+
start = TimeHandler.get_time().replace(hour=0, minute=0, second=0, microsecond=0)
8282
end = start + timedelta(days=1)
8383
# end = start + timedelta(hours=10)
8484
# start = datetime.now(tz=TimeHandler.get_timezone())

source/tibber_api_handler.py

+3-5
Original file line numberDiff line numberDiff line change
@@ -169,7 +169,7 @@ def _remove_energy_rates_from_the_past(self, all_energy_rates: list[EnergyRate])
169169
Returns:
170170
A list of EnergyRate objects that have timestamps in the future relative to the beginning of the current hour.
171171
"""
172-
current_time = datetime.now(tz=all_energy_rates[0].timestamp.tzinfo)
172+
current_time = TimeHandler.get_time()
173173
beginning_of_current_hour = current_time.replace(minute=0, second=0, microsecond=0)
174174

175175
upcoming_energy_rates = [
@@ -285,17 +285,15 @@ def _check_if_minimum_is_at_end_of_day_and_energy_rates_of_tomorrow_are_unavaila
285285
"""
286286

287287
# We use 00:01 instead of 00:00 since the software runs just a few (milli)seconds after the start of the hour
288-
end_of_day = (datetime.now(tz=TimeHandler.get_timezone()) + timedelta(days=1)).replace(
289-
hour=0, minute=1, second=0, microsecond=0
290-
)
288+
end_of_day = (TimeHandler.get_time() + timedelta(days=1)).replace(hour=0, minute=1, second=0, microsecond=0)
291289
three_hours_before_end_of_day = end_of_day - timedelta(hours=3)
292290

293291
is_price_minimum_near_end_of_day = three_hours_before_end_of_day <= price_minimum.timestamp <= end_of_day
294292
self.log.trace(
295293
f"The price minimum {price_minimum.timestamp} is at the end of the day: {is_price_minimum_near_end_of_day}"
296294
)
297295

298-
today = datetime.now().date()
296+
today = TimeHandler.get_time().date()
299297
are_tomorrows_rates_unavailable = not all(rate.timestamp.date() == today for rate in upcoming_energy_rates)
300298
self.log.trace(f"The price rates for tomorrow are unavailable: {are_tomorrows_rates_unavailable}")
301299

source/time_handler.py

+13-1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
from datetime import datetime, time, timedelta
1+
from datetime import date, datetime, time, timedelta
22

33
from dateutil.tz import tz, tzfile
44

@@ -95,3 +95,15 @@ def calculate_day_night_duration(
9595
@staticmethod
9696
def get_timezone() -> tzfile:
9797
return tz.gettz()
98+
99+
@staticmethod
100+
def get_time() -> datetime:
101+
return datetime.now(tz=(TimeHandler.get_timezone()))
102+
103+
@staticmethod
104+
def get_date() -> date:
105+
return TimeHandler.get_time().date()
106+
107+
@staticmethod
108+
def get_date_as_string() -> str:
109+
return TimeHandler.get_date().strftime("%Y-%m-%d")

0 commit comments

Comments
 (0)