本文整理汇总了Python中netCDF4.num2date方法的典型用法代码示例。如果您正苦于以下问题:Python netCDF4.num2date方法的具体用法?Python netCDF4.num2date怎么用?Python netCDF4.num2date使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类netCDF4
的用法示例。
在下文中一共展示了netCDF4.num2date方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: set_time
# 需要导入模块: import netCDF4 [as 别名]
# 或者: from netCDF4 import num2date [as 别名]
def set_time(self, time):
'''
Converts time data into a pandas date object.
Parameters
----------
time: netcdf
Contains time information.
Returns
-------
pandas.DatetimeIndex
'''
times = num2date(time[:].squeeze(), time.units,
only_use_cftime_datetimes=False,
only_use_python_datetimes=True)
self.time = pd.DatetimeIndex(pd.Series(times), tz=self.location.tz)
示例2: _valid_times
# 需要导入模块: import netCDF4 [as 别名]
# 或者: from netCDF4 import num2date [as 别名]
def _valid_times(dataset, variable):
"""Search dataset for time axis"""
var = dataset.variables[variable]
for d in var.dimensions:
if d.startswith('time'):
if d in dataset.variables:
tvar = dataset.variables[d]
return np.array(
netCDF4.num2date(tvar[:], units=tvar.units),
dtype='datetime64[s]')
coords = var.coordinates.split()
for c in coords:
if c.startswith('time'):
tvar = dataset.variables[c]
return np.array(
netCDF4.num2date(tvar[:], units=tvar.units),
dtype='datetime64[s]')
示例3: _map_ini_times_to_paths
# 需要导入模块: import netCDF4 [as 别名]
# 或者: from netCDF4 import num2date [as 别名]
def _map_ini_times_to_paths(self, paths):
"""
.. note:: Potentially expensive I/O operation
"""
mapping = defaultdict(list)
for path in paths:
initial_time = _initial_time(path)
try:
with netCDF4.Dataset(path) as dataset:
if initial_time is None:
var = dataset.variables["forecast_reference_time"]
initial_time = netCDF4.num2date(var[:], units=var.units)
except (FileNotFoundError, KeyError) as ex:
pass
mapping[self.key(initial_time)].append(path)
return mapping
示例4: _times
# 需要导入模块: import netCDF4 [as 别名]
# 或者: from netCDF4 import num2date [as 别名]
def _times(dataset, variable):
"""Find times related to variable in dataset"""
time_dimension = variable.dimensions[0]
coordinates = variable.coordinates.split()
for c in coordinates:
if c.startswith("time"):
try:
var = dataset.variables[c]
return netCDF4.num2date(var[:], units=var.units)
except KeyError:
pass
for v, var in dataset.variables.items():
if len(var.dimensions) != 1:
continue
if v.startswith("time"):
d = var.dimensions[0]
if d == time_dimension:
return netCDF4.num2date(var[:], units=var.units)
示例5: datespan_file
# 需要导入模块: import netCDF4 [as 别名]
# 或者: from netCDF4 import num2date [as 别名]
def datespan_file(self, file):
"""
return the just the day that this argo file covers
"""
nc = seapy.netcdf(file)
try:
d = netCDF4.num2date(nc.variables['JULD'][0],
nc.variables['JULD'].units)
st = datetime.datetime(*d.timetuple()[:3])
en = datetime.datetime(*d.timetuple()[:3] + (23, 59, 59))
except:
st = en = None
pass
finally:
nc.close()
return st, en
示例6: date2num
# 需要导入模块: import netCDF4 [as 别名]
# 或者: from netCDF4 import num2date [as 别名]
def date2num(dates, units, calendar=None):
"""Convert an array of integer into datetime objects.
This function optimizes the date2num function of python-netCDF4 if the
standard calendar is used.
Args:
dates: Either an array of numpy.datetime64 objects (if standard
gregorian calendar is used), otherwise an array of python
datetime objects.
units: A string with the format "{unit} since {epoch}",
e.g. "seconds since 1970-01-01T00:00:00".
calendar: (optional) Standard is gregorian. If others are used,
netCDF4.num2date will be called.
Returns:
An array of integers.
"""
if calendar is None:
calendar = "gregorian"
else:
calendar = calendar.lower()
if calendar != "gregorian":
return netCDF4.date2num(dates, units, calendar)
try:
unit, epoch = units.split(" since ")
except ValueError:
raise InvalidUnitString("Could not convert to numeric values!")
converted_data = \
dates.astype("M8[%s]" % unit_mapper[unit]).astype("int")
# numpy.datetime64 cannot read certain time formats while pandas can.
epoch = pd.Timestamp(epoch).to_datetime64()
if epoch != np.datetime64("1970-01-01"):
converted_data -= np.datetime64("1970-01-01") - epoch
return converted_data
示例7: num2date
# 需要导入模块: import netCDF4 [as 别名]
# 或者: from netCDF4 import num2date [as 别名]
def num2date(times, units, calendar=None):
"""Convert an array of integers into datetime objects.
This function optimizes the num2date function of python-netCDF4 if the
standard calendar is used.
Args:
times: An array of integers representing timestamps.
units: A string with the format "{unit} since {epoch}",
e.g. "seconds since 1970-01-01T00:00:00".
calendar: (optional) Standard is gregorian. If others are used,
netCDF4.num2date will be called.
Returns:
Either an array of numpy.datetime64 objects (if standard gregorian
calendar is used), otherwise an array of python datetime objects.
"""
try:
unit, epoch = units.split(" since ")
except ValueError:
raise InvalidUnitString("Could not convert to datetimes!")
if calendar is None:
calendar = "gregorian"
else:
calendar = calendar.lower()
if calendar != "gregorian":
return netCDF4.num2date(times, units, calendar).astype(
"M8[%s]" % unit_mapper[unit])
# Numpy uses the epoch 1970-01-01 natively.
converted_data = times.astype("M8[%s]" % unit_mapper[unit])
# numpy.datetime64 cannot read certain time formats while pandas can.
epoch = pd.Timestamp(epoch).to_datetime64()
# Maybe there is another epoch used?
if epoch != np.datetime64("1970-01-01"):
converted_data -= np.datetime64("1970-01-01") - epoch
return converted_data
示例8: __read_var
# 需要导入模块: import netCDF4 [as 别名]
# 或者: from netCDF4 import num2date [as 别名]
def __read_var(self, file, var):
ds = Dataset(file, 'r')
self.nx = len(ds.dimensions[self.config.xdim])
self.ny = len(ds.dimensions[self.config.ydim])
self.nt = len(ds.dimensions[self.config.tdim])
self.x = ds.variables[self.config.xname][:]
self.y = ds.variables[self.config.yname][:]
# Sort out the dimensions.
if self.config.clip:
alldims = {}
for key, val in list(ds.dimensions.items()):
alldims[key] = (0, len(val))
vardims = ds.variables[var].dimensions
for clipname in self.config.clip:
clipdims = self.config.clip[clipname]
common = set(alldims.keys()).intersection([clipname])
for k in common:
alldims[k] = clipdims
dims = [alldims[d] for d in vardims]
self.data = np.flipud(np.squeeze(ds.variables[var][
dims[0][0]:dims[0][1],
dims[1][0]:dims[1][1],
dims[2][0]:dims[2][1],
dims[3][0]:dims[3][1]
]))
self.time = ds.variables[self.config.tname][:]
self.Times = []
for t in self.time:
self.Times.append(num2date(
t,
'seconds since {}'.format(self.config.basedate),
calendar=self.config.calendar
))
ds.close()
示例9: initial_time_netcdf4
# 需要导入模块: import netCDF4 [as 别名]
# 或者: from netCDF4 import num2date [as 别名]
def initial_time_netcdf4(self, path):
with netCDF4.Dataset(path) as dataset:
try:
var = dataset.variables["forecast_reference_time"]
result = netCDF4.num2date(var[:], units=var.units)
except KeyError:
result = None
return result
示例10: netcdf4_strategy
# 需要导入模块: import netCDF4 [as 别名]
# 或者: from netCDF4 import num2date [as 别名]
def netcdf4_strategy(path):
with netCDF4.Dataset(path) as dataset:
var = dataset.variables["forecast_reference_time" ]
values = netCDF4.num2date(var[:], units=var.units)
return values
示例11: read_times
# 需要导入模块: import netCDF4 [as 别名]
# 或者: from netCDF4 import num2date [as 别名]
def read_times(path):
"""Read time axis from a file"""
with netCDF4.Dataset(path) as dataset:
var = dataset.variables["time"]
times = netCDF4.num2date(var[:], units=var.units)
return np.array([forest.util.to_datetime(t) for t in times], dtype=object)
示例12: _load_cube
# 需要导入模块: import netCDF4 [as 别名]
# 或者: from netCDF4 import num2date [as 别名]
def _load_cube(self, path, variable, lon0, lat0, pressure=None):
""" Constrain data loading to points required """
cube = iris.load_cube(path, variable)
# reference longitude axis by "axis='X'" and latitude axis as axis='Y',
# to accommodate various types of coordinate system.
# e.g. 'grid_longitude'. See iris.utils.guess_coord_axis.
if cube.coord(axis='X').points[-1] > 180.0:
# get circular longitude values
lon0 = iris.analysis.cartography.wrap_lons(np.asarray(lon0), 0, 360)
# Construct constraint
coord_values={cube.coord(axis='X').standard_name: lon0,
cube.coord(axis='Y').standard_name: lat0,
}
if pressure is not None and 'pressure' in [coord.name() for coord in cube.coords()]:
ptol = 0.01 * pressure
coord_values['pressure'] = (
lambda cell: (pressure - ptol) < cell < (pressure + ptol)
)
cube = cube.extract(iris.Constraint(coord_values=coord_values))
assert cube is not None
# Get validity times and data values
# list the validity times as datetime objects
time_coord = cube.coord('time')
times = time_coord.units.num2date(time_coord.points).tolist()
values = cube.data
return {
"x": times,
"y": values}
示例13: __init__
# 需要导入模块: import netCDF4 [as 别名]
# 或者: from netCDF4 import num2date [as 别名]
def __init__(self, paths):
self.paths = paths
self.table = defaultdict(list)
for path in paths:
time = _initial_time(path)
if time is None:
try:
with netCDF4.Dataset(path) as dataset:
var = dataset.variables["forecast_reference_time"]
time = netCDF4.num2date(var[:], units=var.units)
except KeyError:
continue
self.table[self.key(time)].append(path)
示例14: test_locator_times
# 需要导入模块: import netCDF4 [as 别名]
# 或者: from netCDF4 import num2date [as 别名]
def test_locator_times(tmpdir):
path = str(tmpdir / "eida50_20190417.nc")
with netCDF4.Dataset(path, "w") as dataset:
_eida50(dataset, TIMES, LONS, LATS)
result = eida50.Locator.load_time_axis(path)
with netCDF4.Dataset(path) as dataset:
var = dataset.variables["time"]
expect = netCDF4.num2date(var[:], units=var.units)
np.testing.assert_array_equal(expect, result)
示例15: findLastYearInNCTime
# 需要导入模块: import netCDF4 [as 别名]
# 或者: from netCDF4 import num2date [as 别名]
def findLastYearInNCTime(ncTimeVariable):
# last datetime
last_datetime = nc.num2date(ncTimeVariable[len(ncTimeVariable) - 1],\
ncTimeVariable.units,\
ncTimeVariable.calendar)
return last_datetime.year