From 039673d6094898da10608ed5c2fdf1f5598ffcc1 Mon Sep 17 00:00:00 2001 From: Philipp Jungkamp Date: Thu, 21 Sep 2023 13:29:39 +0200 Subject: [PATCH] python: Always use UTC time when handling Timestamps Signed-off-by: Philipp Jungkamp --- python/villas/node/sample.py | 5 +++-- python/villas/node/test_sample.py | 4 ++-- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/python/villas/node/sample.py b/python/villas/node/sample.py index 1c90b625f..6bb4dc2e4 100644 --- a/python/villas/node/sample.py +++ b/python/villas/node/sample.py @@ -8,7 +8,7 @@ SPDX-License-Identifier: Apache-2.0 import hashlib from ctypes import c_double, c_float, sizeof from dataclasses import dataclass, field -from datetime import datetime +from datetime import datetime, timezone from functools import total_ordering from sys import byteorder as native from typing import Iterable @@ -25,6 +25,7 @@ Signal = bool | int | float | complex class Timestamp: """ A VILLASnode timestamp. Based on the C struct timespec. + These timestamps are always UTC. """ seconds: int @@ -51,7 +52,7 @@ class Timestamp: return float(self) def datetime(self) -> datetime: - return datetime.fromtimestamp(self.timestamp()) + return datetime.fromtimestamp(self.timestamp(), tz=timezone.utc) def __float__(self): return float(self.seconds) + float(self.nanoseconds) * 1e-9 diff --git a/python/villas/node/test_sample.py b/python/villas/node/test_sample.py index 4a723eb44..8e2fbad78 100644 --- a/python/villas/node/test_sample.py +++ b/python/villas/node/test_sample.py @@ -4,7 +4,7 @@ SPDX-FileCopyrightText: 2023 OPAL-RT Germany GmbH SPDX-License-Identifier: Apache-2.0 """ # noqa: E501 from villas.node.sample import Sample, Timestamp, Frame -from datetime import datetime +from datetime import datetime, timezone from cmath import sqrt @@ -21,7 +21,7 @@ def test_timestamp_conversion(): assert ts.timestamp() == fl assert fl_ts == Timestamp.fromtimestamp(fl) - dt = datetime(1973, 11, 29, 22, 33, 9, 123457) + dt = datetime(1973, 11, 29, 21, 33, 9, 123457, tzinfo=timezone.utc) dt_ts = Timestamp(123456789, 123457000) assert ts.datetime() == dt assert dt_ts == Timestamp.fromdatetime(dt)