diff --git a/ecowitt2mqtt/helpers/calculator/time.py b/ecowitt2mqtt/helpers/calculator/time.py index 2598883f..5fcb43cd 100644 --- a/ecowitt2mqtt/helpers/calculator/time.py +++ b/ecowitt2mqtt/helpers/calculator/time.py @@ -1,8 +1,6 @@ """Define time calculators.""" from __future__ import annotations -from datetime import datetime, timezone - from ecowitt2mqtt.const import TIME_SECONDS from ecowitt2mqtt.helpers.calculator import ( CalculatedDataPoint, @@ -11,6 +9,7 @@ SimpleCalculator, ) from ecowitt2mqtt.helpers.typing import PreCalculatedValueType +from ecowitt2mqtt.util.dt import utc_from_timestamp class EpochCalculator(Calculator): @@ -33,7 +32,7 @@ def calculate_from_value( if isinstance(value, str): raise CalculationFailedError("Cannot parse value as datetime") - timestamp = datetime.utcfromtimestamp(value).replace(tzinfo=timezone.utc) + timestamp = utc_from_timestamp(value) return self.get_calculated_data_point(timestamp) diff --git a/ecowitt2mqtt/util/dt.py b/ecowitt2mqtt/util/dt.py new file mode 100644 index 00000000..9cd7431f --- /dev/null +++ b/ecowitt2mqtt/util/dt.py @@ -0,0 +1,22 @@ +"""Define datetime utilities.""" +from datetime import datetime + +try: + from datetime import UTC +except ImportError: + # In place for support of Python 3.10 + from datetime import timezone + + UTC = timezone.utc + + +def utc_from_timestamp(timestamp: float) -> datetime: + """Return a UTC time from a timestamp. + + Args: + timestamp: The epoch to convert. + + Returns: + A parsed ``datetime.datetime`` object. + """ + return datetime.fromtimestamp(timestamp, tz=UTC) diff --git a/pyproject.toml b/pyproject.toml index 8d133baf..b9b44e7f 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -6,7 +6,7 @@ build-backend = "poetry.core.masonry.api" target-version = ["py39"] [tool.coverage.report] -exclude_lines = ["TYPE_CHECKING", "NotImplementedError", "handle_exit_signal"] +exclude_lines = ["TYPE_CHECKING", "ImportError", "NotImplementedError", "handle_exit_signal"] fail_under = 100 show_missing = true @@ -31,7 +31,7 @@ ignore_missing_imports = true no_implicit_optional = true platform = "linux" plugins = ["pydantic.mypy"] -python_version = "3.10" +python_version = "3.12" show_error_codes = true strict_equality = true warn_incomplete_stub = true