diff --git a/dataframely/random.py b/dataframely/random.py index 73388c1..ed4b189 100644 --- a/dataframely/random.py +++ b/dataframely/random.py @@ -352,10 +352,7 @@ def sample_datetime( max_datetime = ( _datetime_to_microseconds(max) if max is not None - else ( - _datetime_to_microseconds(dt.datetime(9999, 12, 31, 23, 59, 59, 999999)) - + 1 - ) + else _default_max_datetime_microseconds(time_zone) ) result = ( self.sample_int( @@ -441,7 +438,22 @@ def _time_to_microseconds(t: dt.time) -> int: return t.microsecond + (t.second + t.minute * 60 + t.hour * 3600) * 10**6 -def _datetime_to_microseconds(dt: dt.datetime) -> int: - return dt.date().toordinal() * SECONDS_PER_DAY * 10**6 + _time_to_microseconds( - dt.time() - ) +def _datetime_to_microseconds(value: dt.datetime) -> int: + microseconds = value.date().toordinal() * SECONDS_PER_DAY * 10**6 + microseconds += _time_to_microseconds(value.time()) + if (offset := value.utcoffset()) is not None: + # Polars stores time zone-aware datetimes as UTC timestamps, so a time + # zone-aware bound must be counted from its UTC time, not its local time. + # Subtract the offset as an integer: converting the datetime to UTC would + # overflow for bounds close to `datetime.min` or `datetime.max`. + microseconds -= offset // dt.timedelta(microseconds=1) + return microseconds + + +def _default_max_datetime_microseconds(time_zone: str | dt.tzinfo | None) -> int: + # The default exclusive upper bound is '10000-01-01' in the output time zone. polars + # resolves the time zone and returns an integer, so this does not overflow either. + last = pl.Series([dt.datetime(9999, 12, 31, 23, 59, 59, 999999)]) + last = last.dt.replace_time_zone(pl.Datetime(time_zone=time_zone).time_zone) + epoch_microseconds = last.dt.epoch("us").item() + return epoch_microseconds + _datetime_to_microseconds(EPOCH_DATETIME) + 1 diff --git a/tests/columns/test_sample.py b/tests/columns/test_sample.py index 7b84cb4..e0fe4b9 100644 --- a/tests/columns/test_sample.py +++ b/tests/columns/test_sample.py @@ -5,6 +5,7 @@ import decimal import math from typing import Any, cast +from zoneinfo import ZoneInfo import polars as pl import pytest @@ -153,6 +154,24 @@ def test_sample_datetime(generator: Generator) -> None: assert samples.max() == dt.datetime(2021, 12, 31) +def test_sample_datetime_time_zone(generator: Generator) -> None: + # Arrange + berlin = ZoneInfo("Europe/Berlin") + column = dy.Datetime( + min=dt.datetime(2020, 1, 1, tzinfo=berlin), + max_exclusive=dt.datetime(2020, 1, 1, 1, tzinfo=berlin), + resolution="1m", + time_zone="Europe/Berlin", + ) + + # Act + samples = sample_and_validate(column, generator, n=10_000) + + # Assert + assert samples.min() == dt.datetime(2020, 1, 1, tzinfo=berlin) + assert samples.max() == dt.datetime(2020, 1, 1, 0, 59, tzinfo=berlin) + + def test_sample_time(generator: Generator) -> None: column = dy.Time(min=dt.time(), max=dt.time(23, 59), resolution="1m") samples = sample_and_validate(column, generator, n=1_000_000) diff --git a/tests/test_random.py b/tests/test_random.py index 5029e82..4e74856 100644 --- a/tests/test_random.py +++ b/tests/test_random.py @@ -4,6 +4,7 @@ import datetime as dt import math from collections.abc import Callable +from zoneinfo import ZoneInfo import numpy as np import polars as pl @@ -145,6 +146,64 @@ def test_sample_binary(generator: Generator) -> None: ) +@pytest.mark.parametrize( + ("lower", "upper", "time_zone"), + [ + *[ + ( + dt.datetime(2020, 1, 1, tzinfo=ZoneInfo(time_zone)), + dt.datetime(2020, 1, 1, 1, tzinfo=ZoneInfo(time_zone)), + time_zone, + ) + for time_zone in ["Europe/Berlin", "America/New_York", "UTC"] + ], + # Both bounds are past `datetime.max` in UTC. + ( + dt.datetime(9999, 12, 31, 20, tzinfo=ZoneInfo("America/New_York")), + dt.datetime(9999, 12, 31, 23, tzinfo=ZoneInfo("America/New_York")), + "America/New_York", + ), + # The default upper bound is '10000-01-01' in the output time zone. + ( + dt.datetime(9999, 12, 31, 20, tzinfo=ZoneInfo("America/New_York")), + None, + "America/New_York", + ), + # Both bounds are before `datetime.min` in UTC. + ( + dt.datetime(1, 1, 1, 0, tzinfo=dt.timezone(dt.timedelta(hours=5))), + dt.datetime(1, 1, 1, 3, tzinfo=dt.timezone(dt.timedelta(hours=5))), + "Etc/GMT-5", + ), + ], +) +def test_sample_datetime_time_zone_aware_bounds( + generator: Generator, + lower: dt.datetime, + upper: dt.datetime | None, + time_zone: str, +) -> None: + # Arrange + # Build the bounds in polars: near the limits, they are outside the range of + # Python datetimes in UTC. + def local(value: dt.datetime) -> pl.Expr: + return pl.lit(value.replace(tzinfo=None)).dt.replace_time_zone(time_zone) + + upper_bound = ( + pl.col("c") < local(upper) + if upper is not None + else pl.col("c") <= local(dt.datetime(9999, 12, 31, 23, 59, 59, 999999)) + ) + + # Act + samples = generator.sample_datetime( + 1_000, min=lower, max=upper, time_zone=time_zone + ).to_frame("c") + + # Assert + assert samples.select(((pl.col("c") >= local(lower)) & upper_bound).all()).item() + + def test_sample_choice(generator: Generator) -> None: samples = generator.sample_choice(100_000, choices=[1, 2, 3]) assert np.allclose(