Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 17 additions & 13 deletions packages/openstef-core/src/openstef_core/utils/datetime.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,17 @@
to regular time grids or specific analysis windows.
"""

import math
from datetime import datetime, time, timedelta
from typing import Literal

import pandas as pd


def align_datetime(timestamp: datetime, interval: timedelta, mode: Literal["ceil", "floor"] = "ceil") -> datetime:
"""Align timestamp using modulo approach.
"""Align timestamp to an interval boundary.

Aware datetimes align on UTC epoch boundaries. Naive datetimes align on boundaries
relative to a naive epoch, so the result does not depend on the local time zone of the machine.

Args:
timestamp: The datetime to align.
Expand All @@ -28,20 +32,20 @@ def align_datetime(timestamp: datetime, interval: timedelta, mode: Literal["ceil
Raises:
ValueError: If mode is not "ceil" or "floor".
"""
timestamp_epoch_seconds = timestamp.timestamp()
interval_seconds = interval.total_seconds()

if mode == "floor":
aligned_secs = math.floor(timestamp_epoch_seconds / interval_seconds) * interval_seconds
elif mode == "ceil":
aligned_secs = math.ceil(timestamp_epoch_seconds / interval_seconds) * interval_seconds
else:
if mode not in {"ceil", "floor"}:
msg = f"Unknown alignment mode: {mode}"
raise ValueError(msg)

if timestamp.tzinfo is None:
return datetime.fromtimestamp(aligned_secs, tz=None) # noqa: DTZ006
return datetime.fromtimestamp(aligned_secs, tz=timestamp.tzinfo)
aligned = pd.Timestamp(timestamp)
if timestamp.tzinfo is not None:
aligned = aligned.tz_convert("UTC")

aligned = aligned.floor(interval) if mode == "floor" else aligned.ceil(interval)

if timestamp.tzinfo is not None:
aligned = aligned.tz_convert(timestamp.tzinfo)

return aligned.to_pydatetime()


def align_datetime_to_time(timestamp: datetime, align_time: time, mode: Literal["ceil", "floor"] = "ceil") -> datetime:
Expand Down
66 changes: 66 additions & 0 deletions packages/openstef-core/tests/unit/utils/test_datetime.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,10 @@

"""Tests for datetime utilities."""

import os
import sys
import time as time_module
from collections.abc import Iterator
from datetime import UTC, datetime, time, timedelta, timezone
from typing import Literal

Expand Down Expand Up @@ -70,6 +74,68 @@ def test_align_datetime_naive(
assert result.tzinfo is None


@pytest.fixture
def local_timezone_ist() -> Iterator[None]:
"""Run a test with the process timezone set to UTC+05:30 (no DST)."""
if sys.platform == "win32":
pytest.skip("time.tzset is not available on Windows")

previous = os.environ.get("TZ")
os.environ["TZ"] = "IST-5:30"
time_module.tzset()
yield
if previous is None:
os.environ.pop("TZ", None)
else:
os.environ["TZ"] = previous
time_module.tzset()


@pytest.mark.parametrize(
("timestamp", "interval", "mode", "expected"),
[
pytest.param(
datetime.fromisoformat("2020-01-01T10:15:00"),
timedelta(hours=1),
"ceil",
datetime.fromisoformat("2020-01-01T11:00:00"),
id="ceil_hour",
),
pytest.param(
datetime.fromisoformat("2020-01-01T10:00:00"),
timedelta(hours=1),
"ceil",
datetime.fromisoformat("2020-01-01T10:00:00"),
id="ceil_already_aligned",
),
pytest.param(
datetime.fromisoformat("2020-01-01T10:45:00"),
timedelta(hours=1),
"floor",
datetime.fromisoformat("2020-01-01T10:00:00"),
id="floor_hour",
),
pytest.param(
datetime.fromisoformat("2020-01-01T10:07:30"),
timedelta(minutes=15),
"ceil",
datetime.fromisoformat("2020-01-01T10:15:00"),
id="ceil_15_minutes",
),
],
)
@pytest.mark.usefixtures("local_timezone_ist")
def test_align_datetime_naive_ignores_local_utc_offset(
timestamp: datetime, interval: timedelta, mode: Literal["ceil", "floor"], expected: datetime
):
# Arrange / Act
result = align_datetime(timestamp, interval, mode)

# Assert
assert result == expected
assert result.tzinfo is None


def test_align_datetime_with_timezone():
# Arrange
tz = UTC
Expand Down