From 5b66ef4bea6ad222033e5d4e67bea59c7ecea7c1 Mon Sep 17 00:00:00 2001 From: Matthias Date: Sun, 14 May 2023 11:02:11 +0200 Subject: [PATCH] Implement datetime.floor --- freqtrade/util/__init__.py | 3 ++- freqtrade/util/datetime_helpers.py | 10 +++++++++- tests/utils/test_datetime_helpers.py | 10 +++++++--- 3 files changed, 18 insertions(+), 5 deletions(-) diff --git a/freqtrade/util/__init__.py b/freqtrade/util/__init__.py index 67cdafc3c..b28544fd3 100644 --- a/freqtrade/util/__init__.py +++ b/freqtrade/util/__init__.py @@ -1,4 +1,4 @@ -from freqtrade.util.datetime_helpers import dt_from_ts, dt_now, dt_ts +from freqtrade.util.datetime_helpers import dt_floor_day, dt_from_ts, dt_now, dt_ts from freqtrade.util.ft_precise import FtPrecise from freqtrade.util.periodic_cache import PeriodicCache @@ -7,6 +7,7 @@ __all__ = [ 'dt_from_ts', 'dt_now', 'dt_ts', + 'dt_floor_day', 'FtPrecise', 'PeriodicCache', ] diff --git a/freqtrade/util/datetime_helpers.py b/freqtrade/util/datetime_helpers.py index 9e7f0a8a8..228bca185 100644 --- a/freqtrade/util/datetime_helpers.py +++ b/freqtrade/util/datetime_helpers.py @@ -8,12 +8,20 @@ def dt_now() -> datetime: def dt_ts(dt: Optional[datetime] = None) -> int: - """Return the current timestamp in ms as a timestamp in UTC.""" + """ + Return dt in ms as a timestamp in UTC. + If dt is None, return the current datetime in UTC. + """ if dt: return int(dt.timestamp() * 1000) return int(dt_now().timestamp() * 1000) +def dt_floor_day(dt: datetime) -> datetime: + """Return the floor of the day for the given datetime.""" + return dt.replace(hour=0, minute=0, second=0, microsecond=0) + + def dt_from_ts(timestamp: float) -> datetime: """ Return a datetime from a timestamp. diff --git a/tests/utils/test_datetime_helpers.py b/tests/utils/test_datetime_helpers.py index 47487a04b..7cff44847 100644 --- a/tests/utils/test_datetime_helpers.py +++ b/tests/utils/test_datetime_helpers.py @@ -3,7 +3,7 @@ from datetime import datetime, timedelta, timezone import pytest import time_machine -from freqtrade.util import dt_from_ts, dt_now, dt_ts +from freqtrade.util import dt_floor_day, dt_from_ts, dt_now, dt_ts def test_dt_now(): @@ -21,8 +21,6 @@ def test_dt_now(): assert dt_ts(now) == int(now.timestamp() * 1000) - - @pytest.mark.parametrize('as_ms', [True, False]) def test_dt_from_ts(as_ms): multi = 1000 if as_ms else 1 @@ -34,3 +32,9 @@ def test_dt_from_ts(as_ms): # 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) + + +def test_dt_floor_day(): + now = datetime(2023, 9, 1, 5, 2, 3, 455555, tzinfo=timezone.utc) + + assert dt_floor_day(now) == datetime(2023, 9, 1, tzinfo=timezone.utc)