本文整理汇总了Python中netCDF4.date2num方法的典型用法代码示例。如果您正苦于以下问题:Python netCDF4.date2num方法的具体用法?Python netCDF4.date2num怎么用?Python netCDF4.date2num使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类netCDF4
的用法示例。
在下文中一共展示了netCDF4.date2num方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: testfile85
# 需要导入模块: import netCDF4 [as 别名]
# 或者: from netCDF4 import date2num [as 别名]
def testfile85(random_field, tempsrcdir):
"""Create a bunch of sample monthly netcdf files with real times"""
dates = [
datetime.datetime(1985, 1, 1) + datetime.timedelta(days=d)
for d in range(0, 365)
]
filename = os.path.join(tempsrcdir, "85.nc")
dataset = netCDF4.Dataset(filename, "w")
shape = random_field.shape
dataset.createDimension("dim0", shape[0])
dataset.createDimension("dim1", shape[1])
dataset.createDimension("time", len(dates))
var = dataset.createVariable("random", "f8", ("time", "dim0", "dim1"))
time = dataset.createVariable("time", "f8", ("time",))
time.units = _UNITS_STD_TIME
time.calendar = _CALENDAR_NO_LEAP
var[:, :, :] = random_field
time[:] = netCDF4.date2num(dates, _UNITS_STD_TIME, calendar=_CALENDAR_NO_LEAP)
dataset.close()
return filename
示例2: monthly_filelist
# 需要导入模块: import netCDF4 [as 别名]
# 或者: from netCDF4 import date2num [as 别名]
def monthly_filelist(random_field, monthlydatetimelist, tempsrcdir):
"""Create a bunch of sample monthly netcdf files with real times"""
file_list = []
for date in monthlydatetimelist:
filename = date.strftime(_DATESTR_FORMAT_MONTHLY)
filename = os.path.join(tempsrcdir, filename)
dataset = netCDF4.Dataset(filename, "w")
shape = random_field.shape
dataset.createDimension("dim0", shape[0])
dataset.createDimension("dim1", shape[1])
dataset.createDimension("time", 1)
var = dataset.createVariable("random", "f8", ("time", "dim0", "dim1"))
time = dataset.createVariable("time", "f8", ("time",))
time.units = _UNITS_STD_TIME
time.calendar = _CALENDAR_NO_LEAP
var[:, :, :] = random_field
time[:] = netCDF4.date2num(date, _UNITS_STD_TIME, calendar=_CALENDAR_NO_LEAP)
dataset.close()
file_list.append(filename)
return file_list
示例3: testfiles8589
# 需要导入模块: import netCDF4 [as 别名]
# 或者: from netCDF4 import date2num [as 别名]
def testfiles8589(random_field, tempsrcdir):
"""Create a bunch of sample monthly netcdf files with real times"""
filelist = []
for year in range(1985, 1990):
date = datetime.datetime(year, 1, 1)
filename = date.strftime("%y.nc")
filename = os.path.join(tempsrcdir, filename)
dataset = netCDF4.Dataset(filename, "w")
shape = random_field.shape
dataset.createDimension("dim0", shape[0])
dataset.createDimension("dim1", shape[1])
dataset.createDimension("time")
var = dataset.createVariable("random", "f8", ("time", "dim0", "dim1"))
time = dataset.createVariable("time", "f8", ("time",))
time.units = _UNITS_STD_TIME
time.calendar = _CALENDAR_NO_LEAP
var[0, :, :] = random_field
time[:] = netCDF4.date2num(date, _UNITS_STD_TIME, calendar=_CALENDAR_NO_LEAP)
dataset.close()
filelist.append(filename)
return filelist
示例4: testfileglobal
# 需要导入模块: import netCDF4 [as 别名]
# 或者: from netCDF4 import date2num [as 别名]
def testfileglobal(tempsrcdir):
"""Create a bunch of sample monthly netcdf files with real times"""
dates = [datetime.datetime.now()]
filename = os.path.join(tempsrcdir, "global.nc")
dataset = netCDF4.Dataset(filename, "w")
random_field = np.random.rand(1, 180, 360) # 1degree resolution
shape = random_field.shape
dataset.createDimension("lat", shape[1])
dataset.createDimension("lon", shape[2])
dataset.createDimension("time", len(dates))
var = dataset.createVariable("random", "f8", ("time", "lat", "lon"))
lon = dataset.createVariable("lon", "f8", ("lon",))
lat = dataset.createVariable("lat", "f8", ("lat",))
time = dataset.createVariable("time", "f8", ("time",))
time.units = _UNITS_STD_TIME
time.calendar = _CALENDAR_NO_LEAP
var[:, :, :] = random_field
time[:] = netCDF4.date2num(dates, _UNITS_STD_TIME, calendar=_CALENDAR_NO_LEAP)
lat[:] = np.linspace(-90.0, 90.0, shape[1])
lon[:] = np.linspace(-180.0, 180, shape[2])
dataset.close()
return filename
示例5: test_main_saves_times_in_database
# 需要导入模块: import netCDF4 [as 别名]
# 或者: from netCDF4 import date2num [as 别名]
def test_main_saves_times_in_database(self):
times = [
dt.datetime(2019, 1, 1, 12),
dt.datetime(2019, 1, 1, 13)]
with netCDF4.Dataset(self.netcdf_file, "w") as dataset:
dataset.createDimension("time", len(times))
obj = dataset.createVariable("time", "d", ("time",))
obj.units = self.units
obj[:] = netCDF4.date2num(times, self.units)
obj = dataset.createVariable("air_temperature", "f", ("time",))
obj.um_stash_source = "m01s16i203"
main.main([
"--database", self.database_file,
self.netcdf_file
])
connection = sqlite3.connect(self.database_file)
cursor = connection.cursor()
cursor.execute("SELECT DISTINCT value FROM time")
result = cursor.fetchall()
expect = [("2019-01-01 12:00:00",), ("2019-01-01 13:00:00",)]
self.assertEqual(expect, result)
示例6: test_main_saves_reference_time
# 需要导入模块: import netCDF4 [as 别名]
# 或者: from netCDF4 import date2num [as 别名]
def test_main_saves_reference_time(self):
reference_time = dt.datetime(2019, 1, 1)
with netCDF4.Dataset(self.netcdf_file, "w") as dataset:
obj = dataset.createVariable("forecast_reference_time", "d", ())
obj[:] = netCDF4.date2num(reference_time, self.units)
obj.units = self.units
main.main([
"--database", self.database_file,
self.netcdf_file
])
connection = sqlite3.connect(self.database_file)
cursor = connection.cursor()
cursor.execute("SELECT reference FROM file")
result = cursor.fetchall()
expect = [(str(reference_time),)]
self.assertEqual(expect, result)
示例7: test_main_saves_axis_information
# 需要导入模块: import netCDF4 [as 别名]
# 或者: from netCDF4 import date2num [as 别名]
def test_main_saves_axis_information(self):
times = [dt.datetime(2019, 1, 1), dt.datetime(2019, 1, 1)]
pressures = [1000, 900]
with netCDF4.Dataset(self.netcdf_file, "w") as dataset:
dataset.createDimension("dim0", len(times))
obj = dataset.createVariable("time", "d", ("dim0",))
obj.units = self.units
obj[:] = netCDF4.date2num(times, self.units)
obj = dataset.createVariable("pressure", "d", ("dim0",))
obj[:] = pressures
obj = dataset.createVariable("air_temperature", "f", ("dim0",))
obj.um_stash_source = "m01s16i203"
obj.coordinates = "time pressure"
main.main([
"--database", self.database_file,
self.netcdf_file
])
connection = sqlite3.connect(self.database_file)
cursor = connection.cursor()
cursor.execute("SELECT v.time_axis, v.pressure_axis FROM variable AS v")
result = cursor.fetchall()
expect = [(0, 0)]
self.assertEqual(expect, result)
示例8: test_valid_times
# 需要导入模块: import netCDF4 [as 别名]
# 或者: from netCDF4 import date2num [as 别名]
def test_valid_times(self):
units = "hours since 1970-01-01 00:00:00"
times = {
"time_0": [dt.datetime(2019, 1, 1)],
"time_1": [dt.datetime(2019, 1, 1, 3)]}
with netCDF4.Dataset(self.path, "w") as dataset:
um = tutorial.UM(dataset)
for name, values in times.items():
var = um.times(name, length=len(values))
var[:] = netCDF4.date2num(values, units=var.units)
var = um.pressures("pressure", length=1)
var[:] = 1000.
var = um.longitudes(length=1)
var[:] = 125.
var = um.latitudes(length=1)
var[:] = 45.
dims = ("time_1", "pressure", "longitude", "latitude")
var = um.relative_humidity(dims)
var[:] = 100.
variable = "relative_humidity"
result = unified_model.read_valid_times(self.path, variable)
expect = times["time_1"]
np.testing.assert_array_equal(expect, result)
示例9: dataList2NetCDF
# 需要导入模块: import netCDF4 [as 别名]
# 或者: from netCDF4 import date2num [as 别名]
def dataList2NetCDF(self, ncFileName, shortVarNameList, varFieldList, timeStamp, posCnt = None):
rootgrp = nc.Dataset(ncFileName,'a')
date_time = rootgrp.variables['time']
if posCnt == None: posCnt = len(date_time)
for shortVarName in shortVarNameList:
date_time[posCnt] = nc.date2num(timeStamp,date_time.units,date_time.calendar)
varField = varFieldList[shortVarName]
# flip variable if necessary (to follow cf_convention)
if self.netcdf_y_orientation_follow_cf_convention: varField = np.flipud(varField)
rootgrp.variables[shortVarName][posCnt,:,:] = varField
rootgrp.sync()
rootgrp.close()
示例10: convert_to_timestamp
# 需要导入模块: import netCDF4 [as 别名]
# 或者: from netCDF4 import date2num [as 别名]
def convert_to_timestamp(self, date: str):
"""Converts ISO 8601 Extended date, to the corresponding dataset time index.
"""
# Time is in ISO 8601 Extended format
# Get time index from dataset
time_range = [dateutil.parser.parse(x) for x in date.split(',')]
time_var = self.time_variable
time_range[0] = time_range[0].replace(tzinfo=None)
time_range = [netCDF4.date2num(
x, time_var.attrs['units']) for x in time_range]
time_range = [np.where(time_var.values == x)[0] for x in time_range]
if len(time_range) == 1: # Single Date
return int(str(time_range[0][0]))
else: # Multiple Dates
date_formatted = {}
i = 0
for x in date.split(','): # x is a single date
new_date = {x: int(str(time_range[i][0]))}
date_formatted.update(new_date) # Add Next pair
i += 1
return date_formatted
示例11: date2num
# 需要导入模块: import netCDF4 [as 别名]
# 或者: from netCDF4 import date2num [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
示例12: interp_data
# 需要导入模块: import netCDF4 [as 别名]
# 或者: from netCDF4 import date2num [as 别名]
def interp_data(self, latitude, longitude, utc_time, param):
"""
Interpolate ``param`` values to ``utc_time`` using indices nearest to
(``latitude, longitude``).
Parmaeters
----------
latitude : float
Latitude in degrees
longitude : float
Longitude in degrees
utc_time : datetime.datetime or datetime.date
Naive or UTC date or datetime to interpolate
param : str
Name of the parameter to interpolate from the data
Returns
-------
Interpolated ``param`` value at (``utc_time, latitude, longitude``)
Examples
--------
Use this to get a single value of a parameter in the data at a specific
time and set of (latitude, longitude) coordinates.
>>> from datetime import datetime
>>> from pvlib.iotools import ecmwf_macc
>>> data = ecmwf_macc.ECMWF_MACC('aod_tcwv_20121101.nc')
>>> dt = datetime(2012, 11, 1, 11, 33, 1)
>>> data.interp_data(38.2, -122.1, dt, 'aod550')
"""
nctime = self.data['time'] # time
ilat, ilon = self.get_nearest_indices(latitude, longitude)
# time index before
before = netCDF4.date2index(utc_time, nctime, select='before')
fbefore = self.data[param][before, ilat, ilon]
fafter = self.data[param][before + 1, ilat, ilon]
dt_num = netCDF4.date2num(utc_time, nctime.units)
time_ratio = (dt_num - nctime[before]) / self.delta_time
return fbefore + (fafter - fbefore) * time_ratio
示例13: build_um
# 需要导入模块: import netCDF4 [as 别名]
# 或者: from netCDF4 import date2num [as 别名]
def build_um(build_dir):
nx, ny = 100, 100
x = np.linspace(0, 45, nx)
y = np.linspace(0, 45, ny)
X, Y = np.meshgrid(x, y)
Z_0 = np.sqrt(X**2 + Y**2)
Z_1 = Z_0 + 5.
reference = dt.datetime(2019, 4, 17)
times = [dt.datetime(2019, 4, 17, 12, 45), dt.datetime(2019, 4, 17, 13, 45)]
path = os.path.join(build_dir, UM_FILE)
print("writing: {}".format(path))
with netCDF4.Dataset(path, "w") as dataset:
formatter = UM(dataset)
var = formatter.longitudes(nx)
var[:] = x
var = formatter.latitudes(ny)
var[:] = y
var = formatter.times("time", length=len(times), dim_name="dim0")
var[:] = netCDF4.date2num(times, units=var.units)
formatter.forecast_reference_time(times[0])
var = formatter.pressures("pressure", length=len(times), dim_name="dim0")
var[:] = 1000.
dims = ("dim0", "longitude", "latitude")
coordinates = "forecast_period_1 forecast_reference_time pressure time"
var = formatter.relative_humidity(dims, coordinates=coordinates)
var[0] = Z_0.T
var[1] = Z_1.T
示例14: forecast_reference_time
# 需要导入模块: import netCDF4 [as 别名]
# 或者: from netCDF4 import date2num [as 别名]
def forecast_reference_time(self, time, name="forecast_reference_time"):
dataset = self.dataset
var = dataset.createVariable(name, "d", ())
var.units = self.units
var.standard_name = name
var.calendar = "gregorian"
var[:] = netCDF4.date2num(time, units=self.units)
示例15: variable_surface
# 需要导入模块: import netCDF4 [as 别名]
# 或者: from netCDF4 import date2num [as 别名]
def variable_surface(
dataset,
variable,
times,
longitudes,
latitudes,
values):
dataset.createDimension("latitude", len(latitudes))
dataset.createDimension("longitude", len(longitudes))
dataset.createDimension("time", len(times))
var = dataset.createVariable(
"longitude", "d", ("longitude",))
var.axis = "X"
var.units = "degrees_east"
var.standard_name = "longitude"
var[:] = longitudes
var = dataset.createVariable(
"latitude", "d", ("latitude",))
var.axis = "Y"
var.units = "degrees_north"
var.standard_name = "latitude"
var[:] = latitudes
units = "hours since 1970-01-01 00:00:00"
var = dataset.createVariable(
"time", "d", ("time",))
var.units = units
var[:] = netCDF4.date2num(times, units=units)
var = dataset.createVariable(
variable, "f",
("time", "latitude", "longitude"))
var.units = "Pa"
var.grid_mapping = "latitude_longitude"
var.coordinates = "forecast_period forecast_reference_time"
var[:] = values