You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
fix: Respect the time zone of datetime bounds when sampling - #428
Generator.sample_datetime ignores the time zone of time zone-aware min / max bounds. It converts each bound to an integer from its local wall-clock time, then casts the sampled integers to pl.Datetime(time_zone=...), which reads them as UTC timestamps. For a zone other than UTC, the sampled range is therefore shifted by the UTC offset:
importdatetimeasdtfromzoneinfoimportZoneInfoimportdataframelyasdyberlin=ZoneInfo("Europe/Berlin")
g=dy.random.Generator(seed=1)
g.sample_datetime(
3,
min=dt.datetime(2020, 1, 1, tzinfo=berlin),
max=dt.datetime(2020, 1, 1, 1, tzinfo=berlin),
time_zone="Europe/Berlin",
)
# -> values between 01:00 and 02:00 Berlin time, all outside [00:00, 01:00)
Because of this, Schema.sample fails for a narrow time zone-aware dy.Datetime range:
classS(dy.Schema):
c=dy.Datetime(
time_zone="Europe/Berlin",
min=dt.datetime(2020, 1, 1, tzinfo=berlin),
max_exclusive=dt.datetime(2020, 1, 1, 1, tzinfo=berlin),
)
S.sample(5)
# ValueError: After sampling for 10000 iterations, no valid data frame was found. ...
For wider ranges, sampling still succeeds, but the samples never cover the part of the range lost to the offset.
Changes
_datetime_to_microseconds in dataframely/random.py converts a time zone-aware value to UTC before counting microseconds. That matches how polars stores time zone-aware datetimes. Naive bounds are handled exactly as before. I also renamed the helper's parameter from dt to value, because it shadowed the datetime module that the conversion needs.
Tests:
tests/test_random.py::test_sample_datetime_time_zone_aware_bounds checks that samples stay within aware bounds for Europe/Berlin, America/New_York, and UTC.
tests/columns/test_sample.py::test_sample_datetime_time_zone samples a one-hour Berlin dy.Datetime column with a 1m resolution and checks that both ends of the range are reached.
Results:
Without the change, 3 of the 4 new test cases fail. The UTC case passes, since it has no offset.
With the change, pytest tests: 2260 passed, 30 skipped, 5 xfailed.
ruff check, ruff format --check, and typos are clean. mypy dataframely/random.py reports one unused-ignore at line 205, which also appears on main without this change.
`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.
The reason will be displayed to describe this comment to others. Learn more.
🟡 Changes recommended
UTC datetime conversion can raise OverflowError for valid timezone-aware bounds near Python’s date limits, causing sampling to fail before generating any values.
This PR corrects datetime sampling so time zone-aware bounds represent the intended UTC instants rather than local wall-clock times. This also fixes sampling for narrow time zone-aware column ranges.
Changes:
Normalize aware bounds to UTC before converting them to microseconds, leaving naive bounds unchanged.
Add generator regression tests for Berlin, New York, and UTC.
Add a column sampling test that checks both endpoints of a minute-resolution Berlin range.
File
Description
tests/test_random.py
Checks that generated datetimes stay within aware bounds across three time zones.
tests/columns/test_sample.py
Checks endpoint coverage for a one-hour, time zone-aware column range.
dataframely/random.py
Converts aware datetime bounds to UTC before calculating microseconds.
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.
The reason will be displayed to describe this comment to others. Learn more.
🔵 Needs a closer look
Datetime sampling fails despite valid remaining local values when max=None because the implicit upper bound is not interpreted in the output time zone.
No open issues 🎉
1 previously missed issue
In code that hasn't changed since last review
Adjust implicit upper boundary to the output time zone
dataframely/random.py:452
With min=datetime(9999, 12, 31, 20, tzinfo=ZoneInfo("America/New_York")), max=None, and time_zone="America/New_York", the adjusted minimum is one hour above the naive fallback maximum at lines 356–357. Sampling therefore fails even though valid local datetimes remain after the minimum. Interpret the implicit upper boundary in the output time zone too, retaining integer arithmetic to avoid overflow, and add a regression case with max=None.
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.
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Motivation
Generator.sample_datetimeignores the time zone of time zone-awaremin/maxbounds. It converts each bound to an integer from its local wall-clock time, then casts the sampled integers topl.Datetime(time_zone=...), which reads them as UTC timestamps. For a zone other than UTC, the sampled range is therefore shifted by the UTC offset:Because of this,
Schema.samplefails for a narrow time zone-awaredy.Datetimerange:For wider ranges, sampling still succeeds, but the samples never cover the part of the range lost to the offset.
Changes
_datetime_to_microsecondsindataframely/random.pyconverts a time zone-aware value to UTC before counting microseconds. That matches how polars stores time zone-aware datetimes. Naive bounds are handled exactly as before. I also renamed the helper's parameter fromdttovalue, because it shadowed thedatetimemodule that the conversion needs.tests/test_random.py::test_sample_datetime_time_zone_aware_boundschecks that samples stay within aware bounds forEurope/Berlin,America/New_York, andUTC.tests/columns/test_sample.py::test_sample_datetime_time_zonesamples a one-hour Berlindy.Datetimecolumn with a1mresolution and checks that both ends of the range are reached.Results:
UTCcase passes, since it has no offset.pytest tests: 2260 passed, 30 skipped, 5 xfailed.ruff check,ruff format --check, andtyposare clean.mypy dataframely/random.pyreports oneunused-ignoreat line 205, which also appears onmainwithout this change.