Implement datetime.floor

This commit is contained in:
Matthias 2023-05-14 11:02:11 +02:00
parent 7f73e99437
commit 5b66ef4bea
3 changed files with 18 additions and 5 deletions

View File

@ -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',
]

View File

@ -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.

View File

@ -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)