Skip to content

Commit 37dad39

Browse files
authored
ENH: Add XTIME fallback for Time coord generation (#170)
1 parent 59cbc05 commit 37dad39

File tree

2 files changed

+36
-8
lines changed

2 files changed

+36
-8
lines changed

tests/test_postprocess.py

+18
Original file line numberDiff line numberDiff line change
@@ -121,6 +121,24 @@ def test_xtime_handling(sample_dataset_with_kwargs, xtime_dtype):
121121
assert np.issubdtype(dataset.XTIME.dtype, xtime_dtype)
122122

123123

124+
@pytest.mark.parametrize(
125+
'sample_dataset_with_kwargs,xtime_dtype',
126+
[
127+
(('wrfout', {'decode_times': True}), np.datetime64),
128+
pytest.param(
129+
('wrfout', {'decode_times': False}),
130+
np.datetime64,
131+
marks=pytest.mark.xfail(raises=ValueError, strict=True),
132+
),
133+
],
134+
indirect=['sample_dataset_with_kwargs'],
135+
)
136+
def test_xtime_fallback(sample_dataset_with_kwargs, xtime_dtype):
137+
dataset_fallback = xwrf.postprocess._decode_times(sample_dataset_with_kwargs.drop_vars('Times'))
138+
dataset = xwrf.postprocess._decode_times(sample_dataset_with_kwargs)
139+
assert dataset_fallback.Time.equals(dataset.Time)
140+
141+
124142
@pytest.mark.parametrize('sample_dataset', ['lambert_conformal'], indirect=True)
125143
def test_assign_coord_to_dim_of_different_name(sample_dataset):
126144
dataset = sample_dataset.pipe(xwrf.postprocess._collapse_time_dim).pipe(

xwrf/postprocess.py

+18-8
Original file line numberDiff line numberDiff line change
@@ -14,14 +14,24 @@ def _decode_times(ds: xr.Dataset) -> xr.Dataset:
1414
"""
1515
Decode the time variable to datetime64.
1616
"""
17-
try:
18-
_time = pd.to_datetime(
19-
ds.Times.data.astype('str'), errors='raise', format='%Y-%m-%d_%H:%M:%S'
20-
)
21-
except ValueError:
22-
_time = pd.to_datetime(
23-
ds.Times.data.astype('str'), errors='raise', format='%Y-%m-%dT%H:%M:%S'
24-
)
17+
if 'Times' in ds:
18+
try:
19+
_time = pd.to_datetime(
20+
ds.Times.data.astype('str'), errors='raise', format='%Y-%m-%d_%H:%M:%S'
21+
)
22+
except ValueError:
23+
_time = pd.to_datetime(
24+
ds.Times.data.astype('str'), errors='raise', format='%Y-%m-%dT%H:%M:%S'
25+
)
26+
elif 'XTIME' in ds:
27+
if ds.XTIME.dtype == 'datetime64[ns]':
28+
_time = ds.XTIME.data
29+
else:
30+
raise ValueError(
31+
'XTIME is not in datetime64 format, please use `xr.open_dataset(..., decode_times=True)`.'
32+
)
33+
else:
34+
raise ValueError('No time variable found in the dataset.')
2535
ds = ds.assign_coords({'Time': _time})
2636
ds.Time.attrs = {'long_name': 'Time', 'standard_name': 'time'}
2737
return ds

0 commit comments

Comments
 (0)