Skip to content

fix: Respect the time zone of datetime bounds when sampling - #428

Merged
Andreas Albert (AndreasAlbertQC) merged 4 commits into
Quantco:mainfrom
fatimaLaraibBonk:fix-sample-datetime-time-zone
Nov 24, 2026
Merged

Andreas Albert (AndreasAlbertQC) merged 4 commits into
Quantco:mainfrom
fatimaLaraibBonk:fix-sample-datetime-time-zone

Conversation

@fatimaLaraibBonk

Copy link
Copy Markdown
Contributor

Motivation

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:

import datetime as dt
from zoneinfo import ZoneInfo
import dataframely as dy

berlin = 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:

class S(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.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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.

1 open issue
What changed in this PR

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.

Review effort: Balanced

Comment thread dataframely/random.py Resolved
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.
Copilot AI balanced review requested due to automatic review settings November 23, 2026 08:52

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Medium severity 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.

1 resolved since last review

Review effort: Balanced

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.
Copilot AI balanced review requested due to automatic review settings November 23, 2026 09:06

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

An unpublished concern about structurally duplicated datetime tests and the repository’s parametrization requirement needs human assessment.

No open issues 🎉

Review effort: Balanced

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.
Copilot AI balanced review requested due to automatic review settings November 23, 2026 09:16

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

Human judgment is needed to determine whether the unpublished nit about duplicated datetime sampling test logic affects approval.

No open issues 🎉

Review effort: Balanced

@codecov

codecov Bot commented Nov 23, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (378c389) to head (28626c2).

Additional details and impacted files
@@            Coverage Diff            @@
##              main      #428   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files           46        46           
  Lines         2592      2601    +9     
=========================================
+ Hits          2592      2601    +9     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for contributing Fatima Laraib (@fatimaLaraibBonk)! This looks good to me, let's go :)

@AndreasAlbertQC
Andreas Albert (AndreasAlbertQC) merged commit c095f4c into Quantco:main Nov 24, 2026
32 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants