Skip to content

Commit

Permalink
cleaned up Time use of netCDF -- it's all in the from_netcdf method now.
Browse files Browse the repository at this point in the history
  • Loading branch information
ChrisBarker-NOAA committed Dec 19, 2024
1 parent d3abfac commit 1207073
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 25 deletions.
4 changes: 2 additions & 2 deletions gridded/tests/test_time.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,8 +35,8 @@ def test_init_with_timeseries():


def test_invalid_timeseries():
with pytest.raises(TypeError):
t = Time("")
with pytest.raises(TypeError, match='not compatible with datetime'):
t = Time(data = ["2012-02-03T12:00"])


def test_from_netcdf_filename_no_var():
Expand Down
20 changes: 12 additions & 8 deletions gridded/time.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ class TimeSeriesError(ValueError):
"""
pass


def offset_as_iso_string(offset_hours):
"""
returns the offset as an isostring:
Expand All @@ -42,6 +43,8 @@ def offset_as_iso_string(offset_hours):


def parse_time_offset(unit_str):
# NOTE: this uses dateutil -- which isn't otherwise required
# we could write it by hand instead.
"""
find the time offset from a CF-style time units string.
Expand Down Expand Up @@ -102,13 +105,6 @@ def __init__(self,
Allows shifting entire time interval into future or past
:type displacement: `datetime.timedelta`
'''
# fixme: This should be happening in various from_netcdf methods.
# if isinstance(data, (nc4.Variable, nc4._netCDF4._Variable)):
# if (hasattr(nc4, 'num2pydate')):
# self.data = nc4.num2pydate(data[:], units=data.units)
# else:
# self.data = nc4.num2date(data[:], units=data.units, only_use_cftime_datetimes=False, only_use_python_datetimes=True)
# elif isinstance(data, Time):
if isinstance(data, Time):
self.data = data.data
elif data is None:
Expand All @@ -119,7 +115,11 @@ def __init__(self,
# Quick check to ensure data is 'datetime-like' enough
# to be compatible with timedelta operations
# fixme: add a try:except around this to raise a meaningful error
self.data += timedelta(seconds=0)

try:
self.data += timedelta(seconds=0)
except TypeError:
raise TypeError(f"Time datatype: {self.data.dtype} not compatible with datetime.")

if origin is not None:
diff = self.data[0] - origin
Expand Down Expand Up @@ -166,6 +166,8 @@ def from_netCDF(cls,
datavar=None,
tz_offset=None,
new_tz_offset=None,
origin=None,
displacement=None,
**kwargs):
"""
construct a Time object from a netcdf file.
Expand Down Expand Up @@ -226,6 +228,8 @@ def from_netCDF(cls,
varname=varname,
tz_offset=tz_offset,
new_tz_offset=new_tz_offset,
origin=origin,
displacement=displacement,
**kwargs
)
return time
Expand Down
34 changes: 19 additions & 15 deletions gridded/variable.py
Original file line number Diff line number Diff line change
Expand Up @@ -245,23 +245,25 @@ def from_netCDF(cls,
units = data.units
except AttributeError:
units = None

if time is None:
timevarname = Time.locate_time_var_from_var(data)
if timevarname is None:
tdata = None
time = Time()
else:
timevar = ds[timevarname]
tdata = nc4.num2date(timevar[:], units=timevar.units, only_use_cftime_datetimes=False, only_use_python_datetimes=True)
# why isn't this using Time.from_netcdf? (currently doesn't support origin and displacement)
time = Time(data=tdata,
time = Time.from_netCDF(
filename=data_file,
dataset=ds,
varname=timevarname,
# datavar=None,
tz_offset=tz_offset,
new_tz_offset=None,
origin=time_origin,
displacement=displacement,
tz_offset=tz_offset)
displacement=displacement
)
else:
timevarname = 1 if len(time) > 1 else 0

if depth is None:
istimevar = 0 if timevarname is None else 1

Expand Down Expand Up @@ -985,19 +987,21 @@ def from_netCDF(cls,
if time is None:
timevarname = Time.locate_time_var_from_var(data)
if timevarname is None:
tdata = None
time = Time()
else:
timevar = ds[timevarname]
tdata = nc4.num2date(timevar[:], units=timevar.units, only_use_cftime_datetimes=False, only_use_python_datetimes=True)
# why isn't this using Time.from_netcdf? (currently doesn't support origin and displacement)
time = Time(data=tdata,
time = Time.from_netCDF(
filename=data_file,
dataset=ds,
varname=timevarname,
# datavar=None,
tz_offset=tz_offset,
new_tz_offset=None,
origin=time_origin,
displacement=displacement,
tz_offset=tz_offset)
displacement=displacement
)
else:
timevarname = 1 if len(time) > 1 else 0

if depth is None:
istimevar = 0 if timevarname is None else 1

Expand Down

0 comments on commit 1207073

Please sign in to comment.