Skip to content
Merged
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
2 changes: 1 addition & 1 deletion ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,7 @@ Band chunking does not help because all selected bands are read together per ite
| `P1Y` | calendar year |
| `PnD` / `PnW` where n > 1 | fixed day windows aligned to 2000-01-01 |

Exact and hourly grouping reject bare dates because `YYYY-MM-DD` is a day-wide `rustac` predicate, not an exact instant. Every bucketed `datetime_filter` is a closed range ending a microsecond before the next bucket, so items in a bucket's last second, such as `23:59:59.5`, are still read.
Calendar and fixed-day windows use each item's UTC date. Exact and hourly grouping reject bare dates because `YYYY-MM-DD` is a day-wide `rustac` predicate, not an exact instant. For bucketed grouping, `datetime_filter` includes both endpoints and ends one microsecond before the next bucket, so it includes timestamps in the last second, such as `23:59:59.5`.

## Mosaic and temporal compositing

Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ da = lazycogs.open(

### Temporal grouping

By default, `lazycogs.open()` groups items into one time step per calendar day (`time_period="P1D"`). You can also request coarser composites with `"PnD"`, `"P1W"`, `"P1M"`, or `"P1Y"`.
By default, `lazycogs.open()` groups items into one time step per UTC calendar day (`time_period="P1D"`). Coarser composites (`"PnD"`, `"P1W"`, `"P1M"`, or `"P1Y"`) also use UTC dates.

For sub-daily collections, two modes are available:

Expand Down
30 changes: 20 additions & 10 deletions src/lazycogs/_temporal.py
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,18 @@ def _parse_timestamp(datetime_str: str) -> datetime:
return parsed.astimezone(UTC)


def _parse_utc_date(datetime_str: str) -> date:
"""Return the UTC calendar date of a timestamp, or a bare date unchanged.

DuckDB returns ``timestamptz`` columns in the session time zone, which
defaults to the system's, so the leading ``YYYY-MM-DD`` of a timestamp
string is not always its UTC date.
"""
if "T" not in datetime_str:
return date.fromisoformat(datetime_str[:10])
return _parse_timestamp(datetime_str).date()


def _format_utc_timestamp(value: datetime, *, timespec: str = "auto") -> str:
"""Return a stable UTC timestamp string ending in ``Z``."""
return value.astimezone(UTC).isoformat(timespec=timespec).replace("+00:00", "Z")
Expand Down Expand Up @@ -160,8 +172,8 @@ class _DayGrouper(_TemporalGrouper):
"""Group items by calendar day (``P1D``)."""

def group_key(self, datetime_str: str) -> str:
"""Return the ``YYYY-MM-DD`` portion of *datetime_str*."""
return datetime_str[:10]
"""Return the UTC ``YYYY-MM-DD`` date of *datetime_str*."""
return _parse_utc_date(datetime_str).isoformat()

def datetime_filter(self, group_key: str) -> str:
"""Return a range covering the whole day."""
Expand All @@ -178,8 +190,7 @@ class _WeekGrouper(_TemporalGrouper):

def group_key(self, datetime_str: str) -> str:
"""Return an ``YYYY-Www`` ISO week label for *datetime_str*."""
d = date.fromisoformat(datetime_str[:10])
iso = d.isocalendar()
iso = _parse_utc_date(datetime_str).isocalendar()
return f"{iso.year}-W{iso.week:02d}"

def datetime_filter(self, group_key: str) -> str:
Expand All @@ -205,8 +216,8 @@ class _MonthGrouper(_TemporalGrouper):
"""Group items by calendar month (``P1M``)."""

def group_key(self, datetime_str: str) -> str:
"""Return the ``YYYY-MM`` portion of *datetime_str*."""
return datetime_str[:7]
"""Return the UTC ``YYYY-MM`` month of *datetime_str*."""
return _parse_utc_date(datetime_str).isoformat()[:7]

def datetime_filter(self, group_key: str) -> str:
"""Return a range covering the full month."""
Expand All @@ -223,8 +234,8 @@ class _YearGrouper(_TemporalGrouper):
"""Group items by calendar year (``P1Y``)."""

def group_key(self, datetime_str: str) -> str:
"""Return the ``YYYY`` portion of *datetime_str*."""
return datetime_str[:4]
"""Return the UTC ``YYYY`` year of *datetime_str*."""
return _parse_utc_date(datetime_str).isoformat()[:4]

def datetime_filter(self, group_key: str) -> str:
"""Return a range covering the full year."""
Expand All @@ -245,8 +256,7 @@ def __init__(self, n_days: int) -> None:

def _bucket(self, datetime_str: str) -> int:
"""Return the zero-based bucket index for *datetime_str*."""
d = date.fromisoformat(datetime_str[:10])
return (d - _EPOCH).days // self._n
return (_parse_utc_date(datetime_str) - _EPOCH).days // self._n

def group_key(self, datetime_str: str) -> str:
"""Return a zero-padded decimal bucket index as the group label."""
Expand Down
40 changes: 40 additions & 0 deletions tests/test_core.py
Original file line number Diff line number Diff line change
Expand Up @@ -157,6 +157,46 @@ def test_build_time_steps_day_two_days():
assert len(time_steps) == 2


def test_build_time_steps_day_uses_utc_midnight_in_non_utc_session(tmp_path):
"""Build UTC day steps whose filters find the right items across midnight."""
parquet = str(tmp_path / "items.parquet")
rustac.write_sync(
parquet,
[
{
"type": "Feature",
"stac_version": "1.0.0",
"id": f"fake-{i}",
"geometry": {"type": "Point", "coordinates": [0.0, 0.0]},
"bbox": [-0.1, -0.1, 0.1, 0.1],
"properties": {"datetime": dt},
"links": [],
"assets": {},
}
for i, dt in enumerate(
["2023-01-15T23:59:59.999999Z", "2023-01-16T00:00:00Z"],
)
],
)
client = DuckdbClient()
client.execute("SET TimeZone = 'Australia/Sydney'")

time_steps = _build_time_steps(
parquet,
duckdb_client=client,
temporal_grouper=_DayGrouper(),
)

assert [step.coord for step in time_steps] == [
np.datetime64("2023-01-15", "D"),
np.datetime64("2023-01-16", "D"),
]
assert [
[item["id"] for item in client.search(parquet, datetime=step.datetime_filter)]
for step in time_steps
] == [["fake-0"], ["fake-1"]]


def test_build_time_steps_month_deduplicates_same_month():
"""Items in the same month collapse to one time step with MonthGrouper."""
table = _items_to_arrow(_FAKE_ITEMS_SAME_MONTH)
Expand Down
15 changes: 15 additions & 0 deletions tests/test_temporal.py
Original file line number Diff line number Diff line change
Expand Up @@ -300,6 +300,21 @@ def test_unsupported_pt_values_raise(self, period):
grouper_from_period(period)


@pytest.mark.parametrize(
("grouper", "datetime_str", "expected"),
[
(_DayGrouper(), "2023-01-16T09:00:00+10:00", "2023-01-15"),
(_WeekGrouper(), "2023-01-16T09:00:00+10:00", "2023-W02"),
(_MonthGrouper(), "2023-02-01T09:00:00+10:00", "2023-01"),
(_YearGrouper(), "2023-01-01T09:00:00+10:00", "2022"),
(_FixedDayGrouper(16), "2023-01-16T09:00:00+10:00", "000525"),
],
)
def test_calendar_groupers_use_utc_date(grouper, datetime_str, expected):
"""Calendar groupers bucket a timestamp by its UTC date, not its local one."""
assert grouper.group_key(datetime_str) == expected


@pytest.mark.parametrize(
"grouper",
[
Expand Down
Loading