gjoseph92 / stackstac

Turn a STAC catalog into a dask-based xarray
https://stackstac.readthedocs.io
MIT License
232 stars 49 forks source link

Error using .sel on time index if timestamp not in np.datetime64 #240

Open JotaFan opened 5 months ago

JotaFan commented 5 months ago

While trying to use .sel to get certain times from the xarray if the timestamp used for compared was not in np.datetime64 it would either:

  1. Not show any result although there was a clear result
  2. Error comparing (using method)

Code to replicate:


import dateutil
import pystac_client
import shapely
import stackstac

URL = "https://earth-search.aws.element84.com/v1"
catalog = pystac_client.Client.open(URL)
collection = ["sentinel-2-l2a"]

start_date = dateutil.parser.parse("2019-03-21")

end_date = dateutil.parser.parse("2019-06-01")

poly_wkt = 'POLYGON ((-6.492295176188869 41.34667865915695, -6.492295176188869 41.35406317236619, -6.512299741612849 41.35406317236619, -6.512299741612849 41.34667865915695, -6.492295176188869 41.34667865915695))'
polygon = shapely.from_wkt(poly_wkt)

dt = f"{start_date.isoformat()}/{end_date.isoformat()}"
items = catalog.search(
    intersects=polygon,
    collections=collection,
    datetime=dt,
).item_collection()

stack = stackstac.stack(items, epsg=32630)

Now to get the erros: <class 'datetime.datetime'>


tt = items[0].datetime
stack.sel(time=tt)

error message: KeyError: "not all values found in index 'time'. Try setting the method keyword argument (example: method='nearest')."

with method: TypeError: Cannot compare dtypes datetime64[ns] and datetime64[ns, tzutc()]

I find an issue was needed, although a easy fix is doable (just pass to np.datatime64), many datasets dont have the timestamp in that format so, an easy fix on this side was just to change the formating whenever the indexing selection occures.

If you agree I can open a PR to solve this