From ace4370da6d2792beee271f48d648d39dab1487e Mon Sep 17 00:00:00 2001 From: fatimaLaraibBonk Date: Sat, 21 Nov 2026 23:13:46 +0500 Subject: [PATCH 1/4] fix: Respect the time zone of datetime bounds when sampling `Generator.sample_datetime` turned `min` and `max` into integers from their local wall-clock time and then read those integers as UTC timestamps. For a time zone-aware bound outside UTC, the sampled range was shifted by the UTC offset, so samples could fall outside the bounds, and `Schema.sample` could fail to find valid data for a narrow `dy.Datetime` range. Convert time zone-aware bounds to UTC before counting microseconds. --- dataframely/random.py | 10 +++++++--- tests/columns/test_sample.py | 14 ++++++++++++++ tests/test_random.py | 15 +++++++++++++++ 3 files changed, 36 insertions(+), 3 deletions(-) diff --git a/dataframely/random.py b/dataframely/random.py index 73388c1a..01221bdb 100644 --- a/dataframely/random.py +++ b/dataframely/random.py @@ -441,7 +441,11 @@ 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: + if value.tzinfo 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. + value = value.astimezone(dt.UTC).replace(tzinfo=None) + return value.date().toordinal() * SECONDS_PER_DAY * 10**6 + _time_to_microseconds( + value.time() ) diff --git a/tests/columns/test_sample.py b/tests/columns/test_sample.py index 7b84cb45..76dec1cb 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,19 @@ def test_sample_datetime(generator: Generator) -> None: assert samples.max() == dt.datetime(2021, 12, 31) +def test_sample_datetime_time_zone(generator: Generator) -> None: + 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", + ) + samples = sample_and_validate(column, generator, n=10_000) + 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 5029e827..4fbfdc82 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,20 @@ def test_sample_binary(generator: Generator) -> None: ) +@pytest.mark.parametrize("time_zone", ["Europe/Berlin", "America/New_York", "UTC"]) +def test_sample_datetime_time_zone_aware_bounds( + generator: Generator, time_zone: str +) -> None: + tz = ZoneInfo(time_zone) + lower = dt.datetime(2020, 1, 1, tzinfo=tz) + upper = dt.datetime(2020, 1, 1, 1, tzinfo=tz) + samples = generator.sample_datetime( + 1_000, min=lower, max=upper, time_zone=time_zone + ) + assert samples.min() >= lower + assert samples.max() < upper + + def test_sample_choice(generator: Generator) -> None: samples = generator.sample_choice(100_000, choices=[1, 2, 3]) assert np.allclose( From 76fa28c17a637a2324391af0408daecf10861f09 Mon Sep 17 00:00:00 2001 From: fatimaLaraibBonk Date: Mon, 23 Nov 2026 13:52:02 +0500 Subject: [PATCH 2/4] fix: Avoid overflow for time zone-aware bounds near the datetime limits Converting a bound to UTC with `astimezone` raises an OverflowError when the UTC time falls outside the range of Python datetimes, for example `datetime(9999, 12, 31, 23, tzinfo=ZoneInfo("America/New_York"))`. Subtract the UTC offset from the microsecond count as an integer instead, which gives the same result without building a UTC datetime. --- dataframely/random.py | 12 +++++++----- tests/test_random.py | 34 ++++++++++++++++++++++++++++++++++ 2 files changed, 41 insertions(+), 5 deletions(-) diff --git a/dataframely/random.py b/dataframely/random.py index 01221bdb..599f7a8d 100644 --- a/dataframely/random.py +++ b/dataframely/random.py @@ -442,10 +442,12 @@ def _time_to_microseconds(t: dt.time) -> int: def _datetime_to_microseconds(value: dt.datetime) -> int: - if value.tzinfo is not None: + 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. - value = value.astimezone(dt.UTC).replace(tzinfo=None) - return value.date().toordinal() * SECONDS_PER_DAY * 10**6 + _time_to_microseconds( - value.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 diff --git a/tests/test_random.py b/tests/test_random.py index 4fbfdc82..ea2493a0 100644 --- a/tests/test_random.py +++ b/tests/test_random.py @@ -160,6 +160,40 @@ def test_sample_datetime_time_zone_aware_bounds( assert samples.max() < upper +@pytest.mark.parametrize( + ("lower", "upper", "time_zone"), + [ + # 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", + ), + # 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_near_limits( + generator: Generator, lower: dt.datetime, upper: dt.datetime, time_zone: str +) -> None: + samples = generator.sample_datetime( + 1_000, min=lower, max=upper, time_zone=time_zone + ).to_frame("c") + + # Build the bounds in polars: they are outside the range of Python datetimes in UTC. + def bound(value: dt.datetime) -> pl.Expr: + return pl.lit(value.replace(tzinfo=None)).dt.replace_time_zone(time_zone) + + in_bounds = samples.select( + (pl.col("c") >= bound(lower)).all() & (pl.col("c") < bound(upper)).all() + ).item() + assert in_bounds + + def test_sample_choice(generator: Generator) -> None: samples = generator.sample_choice(100_000, choices=[1, 2, 3]) assert np.allclose( From 558e6fd6a3f48c6c01adb28b1709e32ec539618e Mon Sep 17 00:00:00 2001 From: fatimaLaraibBonk Date: Mon, 23 Nov 2026 14:06:29 +0500 Subject: [PATCH 3/4] fix: Interpret the default datetime upper bound in the output time zone Without `max`, sample_datetime used '10000-01-01' as a UTC upper bound. For a time zone behind UTC, a valid `min` such as `datetime(9999, 12, 31, 20, tzinfo=ZoneInfo("America/New_York"))` is already past that bound, so sampling failed although valid local datetimes remained. Compute the default bound as '10000-01-01' in the output time zone with polars, which keeps the integer arithmetic and supports every time zone polars accepts. Naive datetimes are unchanged. Also add the arrange-act-assert markers to the new tests and silence the same mypy comparison errors that the other sampling tests ignore. --- dataframely/random.py | 14 ++++++++---- tests/columns/test_sample.py | 5 +++++ tests/test_random.py | 42 ++++++++++++++++++++++++++---------- 3 files changed, 46 insertions(+), 15 deletions(-) diff --git a/dataframely/random.py b/dataframely/random.py index 599f7a8d..ed4b1898 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( @@ -451,3 +448,12 @@ def _datetime_to_microseconds(value: dt.datetime) -> int: # 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 76dec1cb..e0fe4b97 100644 --- a/tests/columns/test_sample.py +++ b/tests/columns/test_sample.py @@ -155,6 +155,7 @@ def test_sample_datetime(generator: Generator) -> None: 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), @@ -162,7 +163,11 @@ def test_sample_datetime_time_zone(generator: Generator) -> None: 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) diff --git a/tests/test_random.py b/tests/test_random.py index ea2493a0..1f0b9ce2 100644 --- a/tests/test_random.py +++ b/tests/test_random.py @@ -150,14 +150,19 @@ def test_sample_binary(generator: Generator) -> None: def test_sample_datetime_time_zone_aware_bounds( generator: Generator, time_zone: str ) -> None: + # Arrange tz = ZoneInfo(time_zone) lower = dt.datetime(2020, 1, 1, tzinfo=tz) upper = dt.datetime(2020, 1, 1, 1, tzinfo=tz) + + # Act samples = generator.sample_datetime( 1_000, min=lower, max=upper, time_zone=time_zone ) - assert samples.min() >= lower - assert samples.max() < upper + + # Assert + assert samples.min() >= lower # type: ignore + assert samples.max() < upper # type: ignore @pytest.mark.parametrize( @@ -169,6 +174,12 @@ def test_sample_datetime_time_zone_aware_bounds( 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))), @@ -178,20 +189,29 @@ def test_sample_datetime_time_zone_aware_bounds( ], ) def test_sample_datetime_time_zone_aware_bounds_near_limits( - generator: Generator, lower: dt.datetime, upper: dt.datetime, time_zone: str + generator: Generator, + lower: dt.datetime, + upper: dt.datetime | None, + time_zone: str, ) -> None: + # Arrange + # Build the bounds in polars: 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") - # Build the bounds in polars: they are outside the range of Python datetimes in UTC. - def bound(value: dt.datetime) -> pl.Expr: - return pl.lit(value.replace(tzinfo=None)).dt.replace_time_zone(time_zone) - - in_bounds = samples.select( - (pl.col("c") >= bound(lower)).all() & (pl.col("c") < bound(upper)).all() - ).item() - assert in_bounds + # Assert + assert samples.select(((pl.col("c") >= local(lower)) & upper_bound).all()).item() def test_sample_choice(generator: Generator) -> None: From 28626c293401fcef66b71344221c528f1c693d9d Mon Sep 17 00:00:00 2001 From: fatimaLaraibBonk Date: Mon, 23 Nov 2026 14:16:50 +0500 Subject: [PATCH 4/4] test: Merge the time zone-aware datetime sampling tests The two tests had the same structure, so parametrize a single test with all cases. Comparing in polars works for every case and no longer needs the type: ignore comments. --- tests/test_random.py | 32 +++++++++++--------------------- 1 file changed, 11 insertions(+), 21 deletions(-) diff --git a/tests/test_random.py b/tests/test_random.py index 1f0b9ce2..4e748565 100644 --- a/tests/test_random.py +++ b/tests/test_random.py @@ -146,28 +146,17 @@ def test_sample_binary(generator: Generator) -> None: ) -@pytest.mark.parametrize("time_zone", ["Europe/Berlin", "America/New_York", "UTC"]) -def test_sample_datetime_time_zone_aware_bounds( - generator: Generator, time_zone: str -) -> None: - # Arrange - tz = ZoneInfo(time_zone) - lower = dt.datetime(2020, 1, 1, tzinfo=tz) - upper = dt.datetime(2020, 1, 1, 1, tzinfo=tz) - - # Act - samples = generator.sample_datetime( - 1_000, min=lower, max=upper, time_zone=time_zone - ) - - # Assert - assert samples.min() >= lower # type: ignore - assert samples.max() < upper # type: ignore - - @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")), @@ -188,14 +177,15 @@ def test_sample_datetime_time_zone_aware_bounds( ), ], ) -def test_sample_datetime_time_zone_aware_bounds_near_limits( +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: they are outside the range of Python datetimes in UTC. + # 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)