Skip to content
Open
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
44 changes: 44 additions & 0 deletions tests/test_bounds.py
Original file line number Diff line number Diff line change
Expand Up @@ -762,6 +762,50 @@ def test_returns_bounds_for_cftime_time_coords_using_freq(self):

assert result.time_bnds.identical(expected_time_bnds)

def test_returns_bounds_for_cftime_time_coords_without_calendar_encoding(self):
# Time coordinates created in memory or returned by Xarray operations
# such as `resample()` do not have a "calendar" encoding.
ds = self.ds.copy()
ds = ds.drop_dims("time")
ds["time"] = xr.DataArray(
name="time",
data=np.array(
[
cftime.DatetimeNoLeap(1850, 1, 1),
cftime.DatetimeNoLeap(1850, 2, 1),
cftime.DatetimeNoLeap(1850, 3, 1),
],
),
dims=["time"],
attrs={"axis": "T", "long_name": "time", "standard_name": "time"},
)

result = ds.bounds.add_time_bounds(method="freq")
expected_time_bnds = xr.DataArray(
name="time_bnds",
data=np.array(
[
[
cftime.DatetimeNoLeap(1850, 1, 1),
cftime.DatetimeNoLeap(1850, 2, 1),
],
[
cftime.DatetimeNoLeap(1850, 2, 1),
cftime.DatetimeNoLeap(1850, 3, 1),
],
[
cftime.DatetimeNoLeap(1850, 3, 1),
cftime.DatetimeNoLeap(1850, 4, 1),
],
],
),
coords={"time": ds.time.assign_attrs({"bounds": "time_bnds"})},
dims=["time", "bnds"],
attrs={"xcdat_bounds": "True"},
)

assert result.time_bnds.identical(expected_time_bnds)

def test_returns_bounds_for_cftime_time_coords_as_midpoints(self):
ds = self.ds.copy()
ds = ds.drop_dims("time")
Expand Down
5 changes: 4 additions & 1 deletion xcdat/bounds.py
Original file line number Diff line number Diff line change
Expand Up @@ -622,7 +622,10 @@ def _create_time_bounds( # noqa: C901
timesteps = pd.to_datetime(timesteps)
obj_type = pd.Timestamp
elif _get_datetime_like_type(time) == cftime.datetime:
calendar = time.encoding["calendar"]
# Get the calendar from the `cftime` objects instead of the
# "calendar" encoding, which is not set for time coordinates created
# in memory or returned by some Xarray operations (e.g., `resample()`).
calendar = time.dt.calendar
obj_type = get_date_type(calendar)

if freq == "year":
Expand Down