Skip to content

Commit 2579d97

Browse files
committed
allow timezone aware time selection
1 parent 03f9148 commit 2579d97

File tree

3 files changed

+51
-0
lines changed

3 files changed

+51
-0
lines changed

CHANGES.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,10 @@
22

33
## Unreleased
44

5+
### titiler.xarray
6+
7+
* add support for timezone aware time selection (e.g `sel="time=2023-01-01T00:00:00+03:00"`)
8+
59
## 0.22.2 (2025-06-02)
610

711
### titiler.application

src/titiler/xarray/tests/test_io_tools.py

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -169,6 +169,46 @@ def test_get_variable():
169169
da = get_variable(ds, "dataset")
170170

171171

172+
def test_get_variable_datetime_tz():
173+
"""test io.get_variable with datetime and timezones."""
174+
arr = numpy.arange(0, 33 * 35 * 2).reshape(2, 33, 35)
175+
data = xarray.DataArray(
176+
arr,
177+
dims=("time", "y", "x"),
178+
coords={
179+
"x": numpy.arange(-170, 180, 10),
180+
"y": numpy.arange(-80, 85, 5),
181+
"time": [
182+
datetime(2022, 1, 1),
183+
datetime(2023, 1, 1),
184+
],
185+
},
186+
)
187+
data.attrs.update({"valid_min": arr.min(), "valid_max": arr.max()})
188+
assert not data.rio.crs
189+
assert data.dims == ("time", "y", "x")
190+
ds = data.to_dataset(name="dataset")
191+
192+
da = get_variable(ds, "dataset", sel=["time=2023-01-01T00:00:00"], method="nearest")
193+
assert da.rio.crs
194+
assert da.dims == ("y", "x")
195+
assert da["time"] == numpy.datetime64("2023-01-01")
196+
197+
da = get_variable(
198+
ds, "dataset", sel=["time=2023-01-01T00:00:00Z"], method="nearest"
199+
)
200+
assert da.rio.crs
201+
assert da.dims == ("y", "x")
202+
assert da["time"] == numpy.datetime64("2023-01-01")
203+
204+
da = get_variable(
205+
ds, "dataset", sel=["time=2023-01-01T00:00:00+03:00"], method="nearest"
206+
)
207+
assert da.rio.crs
208+
assert da.dims == ("y", "x")
209+
assert da["time"] == numpy.datetime64("2023-01-01")
210+
211+
172212
@pytest.mark.parametrize(
173213
"protocol,filename",
174214
[

src/titiler/xarray/titiler/xarray/io.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
import pandas
99
import xarray
1010
from morecantile import TileMatrixSet
11+
from pandas._libs.tslibs.parsing import DateParseError
1112
from rio_tiler.constants import WEB_MERCATOR_TMS
1213
from rio_tiler.io.xarray import XarrayReader
1314
from xarray.namedarray.utils import module_available
@@ -143,6 +144,12 @@ def _cast_to_type(value, dtype: Any) -> Any:
143144
elif numpy.issubdtype(dtype, numpy.floating):
144145
value = float(value)
145146

147+
elif numpy.issubdtype(dtype, numpy.datetime64) or dtype == "O":
148+
try:
149+
value = pandas.Timestamp(value).to_datetime64()
150+
except DateParseError:
151+
pass
152+
146153
return value
147154

148155

0 commit comments

Comments
 (0)