From 6044bbb6b1b9a343edb44cc504d695707b19701f Mon Sep 17 00:00:00 2001 From: Matthias Date: Sun, 14 May 2023 09:28:59 +0200 Subject: [PATCH] Add datetime helpers to unify code --- freqtrade/util/__init__.py | 13 +++++++++++-- freqtrade/util/datetime_helpers.py | 17 ++++++++++++++++ tests/utils/test_datetime_helpers.py | 29 ++++++++++++++++++++++++++++ 3 files changed, 57 insertions(+), 2 deletions(-) create mode 100644 freqtrade/util/datetime_helpers.py create mode 100644 tests/utils/test_datetime_helpers.py diff --git a/freqtrade/util/__init__.py b/freqtrade/util/__init__.py index 3c3c034c1..37d95e511 100644 --- a/freqtrade/util/__init__.py +++ b/freqtrade/util/__init__.py @@ -1,2 +1,11 @@ -from freqtrade.util.ft_precise import FtPrecise # noqa: F401 -from freqtrade.util.periodic_cache import PeriodicCache # noqa: F401 +from freqtrade.util.datetime_helpers import dt_from_ts, dt_now +from freqtrade.util.ft_precise import FtPrecise +from freqtrade.util.periodic_cache import PeriodicCache + + +__all__ = [ + 'dt_from_ts', + 'dt_now', + 'FtPrecise', + 'PeriodicCache', +] diff --git a/freqtrade/util/datetime_helpers.py b/freqtrade/util/datetime_helpers.py new file mode 100644 index 000000000..aa9403cba --- /dev/null +++ b/freqtrade/util/datetime_helpers.py @@ -0,0 +1,17 @@ +from datetime import datetime, timezone + + +def dt_now() -> datetime: + """Return the current datetime in UTC.""" + return datetime.now(timezone.utc) + + +def dt_from_ts(timestamp: float) -> datetime: + """ + Return a datetime from a timestamp. + :param timestamp: timestamp in seconds or milliseconds + """ + if timestamp > 1e10: + # Timezone in ms - convert to seconds + timestamp /= 1000 + return datetime.fromtimestamp(timestamp, tz=timezone.utc) diff --git a/tests/utils/test_datetime_helpers.py b/tests/utils/test_datetime_helpers.py new file mode 100644 index 000000000..947aab1b8 --- /dev/null +++ b/tests/utils/test_datetime_helpers.py @@ -0,0 +1,29 @@ +from datetime import datetime, timedelta, timezone + +import pytest +import time_machine + +from freqtrade.util import dt_from_ts, dt_now + + +def test_dt_now(): + with time_machine.travel("2021-09-01 05:01:00 +00:00", tick=False) as t: + now = datetime.now(timezone.utc) + assert dt_now() == now + + t.shift(timedelta(hours=5)) + assert dt_now() >= now + assert dt_now() == datetime.now(timezone.utc) + + +@pytest.mark.parametrize('as_ms', [True, False]) +def test_dt_from_ts(as_ms): + multi = 1000 if as_ms else 1 + assert dt_from_ts(1683244800.0 * multi) == datetime(2023, 5, 5, tzinfo=timezone.utc) + assert dt_from_ts(1683244800.5555 * multi) == datetime(2023, 5, 5, 0, 0, 0, 555500, + tzinfo=timezone.utc) + # As int + assert dt_from_ts(1683244800 * multi) == datetime(2023, 5, 5, tzinfo=timezone.utc) + # As milliseconds + assert dt_from_ts(1683244800 * multi) == datetime(2023, 5, 5, tzinfo=timezone.utc) + assert dt_from_ts(1683242400 * multi) == datetime(2023, 5, 4, 23, 20, tzinfo=timezone.utc)