From 81d0653560114553c89b1b83174d433c673e57c7 Mon Sep 17 00:00:00 2001 From: Anthony Romaniello <66272872+aromanielloNTIA@users.noreply.github.com> Date: Tue, 25 Apr 2023 11:28:38 -0600 Subject: [PATCH] Fix scheduling future actions (#237) * Fix scheduling future actions * add unit tests for sensor.utils datetime manipulations --- src/sensor/tests/test_sensor_utils.py | 20 ++++++++++++++++++++ src/sensor/utils.py | 8 ++++---- 2 files changed, 24 insertions(+), 4 deletions(-) create mode 100644 src/sensor/tests/test_sensor_utils.py diff --git a/src/sensor/tests/test_sensor_utils.py b/src/sensor/tests/test_sensor_utils.py new file mode 100644 index 00000000..769b82a5 --- /dev/null +++ b/src/sensor/tests/test_sensor_utils.py @@ -0,0 +1,20 @@ +from datetime import datetime + +from django.conf import settings + +from sensor import utils + + +def test_timestamp_manipulation(): + now = datetime.now() + now_int = int(now.timestamp()) + now_fromint = datetime.fromtimestamp(now_int) + now_str = now.strftime(settings.DATETIME_FORMAT) + + test_dt_int = utils.get_timestamp_from_datetime(now) + test_dt_fromint = utils.get_datetime_from_timestamp(now_int) + test_dt_fromstr = utils.parse_datetime_str(now_str) + + assert now_int == test_dt_int + assert now_fromint == test_dt_fromint + assert now == test_dt_fromstr diff --git a/src/sensor/utils.py b/src/sensor/utils.py index fc46980a..af07d057 100644 --- a/src/sensor/utils.py +++ b/src/sensor/utils.py @@ -9,16 +9,16 @@ logger = logging.getLogger(__name__) -def get_datetime_from_timestamp(ts): +def get_datetime_from_timestamp(ts: int) -> datetime: return datetime.fromtimestamp(ts) -def get_timestamp_from_datetime(dt: datetime): +def get_timestamp_from_datetime(dt: datetime) -> int: """Assumes UTC datetime.""" - return int(dt.strftime("%S")) + return int(dt.timestamp()) -def parse_datetime_str(d): +def parse_datetime_str(d: str) -> datetime: return datetime.strptime(d, settings.DATETIME_FORMAT)