当前位置: 首页>>代码示例>>Python>>正文


Python cftime.datetime方法代码示例

本文整理汇总了Python中cftime.datetime方法的典型用法代码示例。如果您正苦于以下问题:Python cftime.datetime方法的具体用法?Python cftime.datetime怎么用?Python cftime.datetime使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在cftime的用法示例。


在下文中一共展示了cftime.datetime方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: datetime_or_default

# 需要导入模块: import cftime [as 别名]
# 或者: from cftime import datetime [as 别名]
def datetime_or_default(date, default):
    """Return a datetime-like object or a default.

    Parameters
    ----------
    date : `None` or datetime-like object or str
    default : The value to return if `date` is `None`

    Returns
    -------
    `default` if `date` is `None`, otherwise returns the result of
    `utils.times.ensure_datetime(date)`

    """
    if date is None:
        return default
    else:
        return ensure_datetime(date) 
开发者ID:spencerahill,项目名称:aospy,代码行数:20,代码来源:times.py

示例2: ensure_datetime

# 需要导入模块: import cftime [as 别名]
# 或者: from cftime import datetime [as 别名]
def ensure_datetime(obj):
    """Return the object if it is a datetime-like object

    Parameters
    ----------
    obj : Object to be tested.

    Returns
    -------
    The original object if it is a datetime-like object

    Raises
    ------
    TypeError if `obj` is not datetime-like
    """
    _VALID_TYPES = (str, datetime.datetime, cftime.datetime,
                    np.datetime64)
    if isinstance(obj, _VALID_TYPES):
        return obj
    raise TypeError("datetime-like object required.  "
                    "Type given: {}".format(type(obj))) 
开发者ID:spencerahill,项目名称:aospy,代码行数:23,代码来源:times.py

示例3: axisinfo

# 需要导入模块: import cftime [as 别名]
# 或者: from cftime import datetime [as 别名]
def axisinfo(unit, axis):
        """
        Returns the :class:`~matplotlib.units.AxisInfo` for *unit*.

        *unit* is a tzinfo instance or None.
        The *axis* argument is required but not used.
        """
        calendar, date_unit, date_type = unit

        majloc = NetCDFTimeDateLocator(4, calendar=calendar,
                                       date_unit=date_unit)
        majfmt = NetCDFTimeDateFormatter(majloc, calendar=calendar,
                                         time_units=date_unit)
        if date_type is CalendarDateTime:
            datemin = CalendarDateTime(cftime.datetime(2000, 1, 1),
                                       calendar=calendar)
            datemax = CalendarDateTime(cftime.datetime(2010, 1, 1),
                                       calendar=calendar)
        else:
            datemin = date_type(2000, 1, 1)
            datemax = date_type(2010, 1, 1)
        return munits.AxisInfo(majloc=majloc, majfmt=majfmt, label='',
                               default_limits=(datemin, datemax)) 
开发者ID:SciTools,项目名称:nc-time-axis,代码行数:25,代码来源:__init__.py

示例4: test_cftime_transform_noleap_warn

# 需要导入模块: import cftime [as 别名]
# 或者: from cftime import datetime [as 别名]
def test_cftime_transform_noleap_warn(self):
        try:
            import cftime
        except:
            raise SkipTest('Test requires cftime library')
        gregorian_dates = [cftime.DatetimeNoLeap(2000, 2, 28),
                           cftime.DatetimeNoLeap(2000, 3, 1),
                           cftime.DatetimeNoLeap(2000, 3, 2)]
        curve = Curve((gregorian_dates, [1, 2, 3]))
        plot = bokeh_renderer.get_plot(curve)
        xs = plot.handles['cds'].data['x']
        self.assertEqual(xs.astype('int64'),
                         np.array([951696000000, 951868800000, 951955200000]))
        substr = (
            "Converting cftime.datetime from a non-standard calendar "
            "(noleap) to a standard calendar for plotting. This may "
            "lead to subtle errors in formatting dates, for accurate "
            "tick formatting switch to the matplotlib backend.")
        self.log_handler.assertEndsWith('WARNING', substr) 
开发者ID:holoviz,项目名称:holoviews,代码行数:21,代码来源:testelementplot.py

示例5: cftime_to_timestamp

# 需要导入模块: import cftime [as 别名]
# 或者: from cftime import datetime [as 别名]
def cftime_to_timestamp(date, time_unit='us'):
    """Converts cftime to timestamp since epoch in milliseconds

    Non-standard calendars (e.g. Julian or no leap calendars)
    are converted to standard Gregorian calendar. This can cause
    extra space to be added for dates that don't exist in the original
    calendar. In order to handle these dates correctly a custom bokeh
    model with support for other calendars would have to be defined.

    Args:
        date: cftime datetime object (or array)

    Returns:
        time_unit since 1970-01-01 00:00:00
    """
    import cftime
    utime = cftime.utime('microseconds since 1970-01-01 00:00:00')
    if time_unit == 'us':
        tscale = 1
    else:
        tscale = (np.timedelta64(1, 'us')/np.timedelta64(1, time_unit))
    return utime.date2num(date)*tscale 
开发者ID:holoviz,项目名称:holoviews,代码行数:24,代码来源:util.py

示例6: ensure_cftime_array

# 需要导入模块: import cftime [as 别名]
# 或者: from cftime import datetime [as 别名]
def ensure_cftime_array(time: Sequence):
    """Convert an input 1D array to an array of cftime objects. Python's datetime are converted to cftime.DatetimeGregorian.

    Raises ValueError when unable to cast the input.
    """
    if isinstance(time, xr.DataArray):
        time = time.indexes["time"]
    elif isinstance(time, np.ndarray):
        time = pd.DatetimeIndex(time)
    if isinstance(time[0], cftime.datetime):
        return time
    if isinstance(time[0], pydt.datetime):
        return np.array(
            [cftime.DatetimeGregorian(*ele.timetuple()[:6]) for ele in time]
        )
    raise ValueError("Unable to cast array to cftime dtype") 
开发者ID:Ouranosinc,项目名称:xclim,代码行数:18,代码来源:calendar.py

示例7: cfindex_start_time

# 需要导入模块: import cftime [as 别名]
# 或者: from cftime import datetime [as 别名]
def cfindex_start_time(cfindex, freq):
    """
    Get the start of a period for a pseudo-period index. As we are using
    datetime indices to stand in for period indices, assumptions regarding the
    period are made based on the given freq. IMPORTANT NOTE: this function
    cannot be used on greater-than-day freq that start at the beginning of a
    month, e.g., 'MS', 'QS', 'AS' -- this mirrors pandas behavior.

    Parameters
    __________
    cfindex : CFTimeIndex
        CFTimeIndex as a proxy representation for CFPeriodIndex
    freq : str
        String specifying the frequency/offset such as 'MS', '2D', 'H', or '3T'

    Returns
    _______
    CFTimeIndex
        The starting datetimes of periods inferred from dates and freq
    """
    return CFTimeIndex([cftime_start_time(date, freq) for date in cfindex]) 
开发者ID:Ouranosinc,项目名称:xclim,代码行数:23,代码来源:calendar.py

示例8: cfindex_end_time

# 需要导入模块: import cftime [as 别名]
# 或者: from cftime import datetime [as 别名]
def cfindex_end_time(cfindex, freq):
    """
    Get the start of a period for a pseudo-period index. As we are using
    datetime indices to stand in for period indices, assumptions regarding the
    period are made based on the given freq. IMPORTANT NOTE: this function
    cannot be used on greater-than-day freq that start at the beginning of a
    month, e.g., 'MS', 'QS', 'AS' -- this mirrors pandas behavior.

    Parameters
    __________
    cfindex : CFTimeIndex
        CFTimeIndex as a proxy representation for CFPeriodIndex
    freq : str
        String specifying the frequency/offset such as 'MS', '2D', 'H', or '3T'

    Returns
    _______
    CFTimeIndex
        The ending datetimes of periods inferred from dates and freq
    """
    return CFTimeIndex([cftime_end_time(date, freq) for date in cfindex]) 
开发者ID:Ouranosinc,项目名称:xclim,代码行数:23,代码来源:calendar.py

示例9: apply_time_offset

# 需要导入模块: import cftime [as 别名]
# 或者: from cftime import datetime [as 别名]
def apply_time_offset(time, years=0, months=0, days=0, hours=0):
    """Apply a specified offset to the given time array.

    This is useful for GFDL model output of instantaneous values.  For example,
    3 hourly data postprocessed to netCDF files spanning 1 year each will
    actually have time values that are offset by 3 hours, such that the first
    value is for 1 Jan 03:00 and the last value is 1 Jan 00:00 of the
    subsequent year.  This causes problems in xarray, e.g. when trying to group
    by month.  It is resolved by manually subtracting off those three hours,
    such that the dates span from 1 Jan 00:00 to 31 Dec 21:00 as desired.

    Parameters
    ----------
    time : xarray.DataArray representing a timeseries
    years, months, days, hours : int, optional
        The number of years, months, days, and hours, respectively, to offset
        the time array by.  Positive values move the times later.

    Returns
    -------
    pandas.DatetimeIndex

    Examples
    --------
    Case of a length-1 input time array:

    >>> times = xr.DataArray(datetime.datetime(1899, 12, 31, 21))
    >>> apply_time_offset(times)
    Timestamp('1900-01-01 00:00:00')

    Case of input time array with length greater than one:

    >>> times = xr.DataArray([datetime.datetime(1899, 12, 31, 21),
    ...                       datetime.datetime(1899, 1, 31, 21)])
    >>> apply_time_offset(times) # doctest: +NORMALIZE_WHITESPACE
    DatetimeIndex(['1900-01-01', '1899-02-01'], dtype='datetime64[ns]',
                  freq=None)
    """
    return (pd.to_datetime(time.values) +
            pd.DateOffset(years=years, months=months, days=days, hours=hours)) 
开发者ID:spencerahill,项目名称:aospy,代码行数:42,代码来源:times.py

示例10: average_time_bounds

# 需要导入模块: import cftime [as 别名]
# 或者: from cftime import datetime [as 别名]
def average_time_bounds(ds):
    """Return the average of each set of time bounds in the Dataset.

    Useful for creating a new time array to replace the Dataset's native time
    array, in the case that the latter matches either the start or end bounds.
    This can cause errors in grouping (akin to an off-by-one error) if the
    timesteps span e.g. one full month each.  Note that the Dataset's times
    must not have already undergone "CF decoding", wherein they are converted
    from floats using the 'units' attribute into datetime objects.

    Parameters
    ----------
    ds : xarray.Dataset
        A Dataset containing a time bounds array with name matching
        internal_names.TIME_BOUNDS_STR.  This time bounds array must have two
        dimensions, one of which's coordinates is the Dataset's time array, and
        the other is length-2.

    Returns
    -------
    xarray.DataArray
        The mean of the start and end times of each timestep in the original
        Dataset.

    Raises
    ------
    ValueError
        If the time bounds array doesn't match the shape specified above.

    """
    bounds = ds[TIME_BOUNDS_STR]
    new_times = bounds.mean(dim=BOUNDS_STR, keep_attrs=True)
    new_times = new_times.drop_vars(TIME_STR).rename(TIME_STR)
    new_times[TIME_STR] = new_times
    return new_times 
开发者ID:spencerahill,项目名称:aospy,代码行数:37,代码来源:times.py

示例11: get_time_decoded

# 需要导入模块: import cftime [as 别名]
# 或者: from cftime import datetime [as 别名]
def get_time_decoded(self, midpoint=True):
        """Return time decoded.
        """
        # to compute a time midpoint, we need a time_bound variable
        if midpoint and self.time_bound is None:
            raise ValueError('cannot compute time midpoint w/o time bounds')

        if midpoint:
            time_data = self.time_bound.mean(self.tb_dim)

        else:
            # if time has already been decoded and there's no year_offset,
            # just return the time as is
            if self.isdecoded(self.time):
                if self.year_offset is None:
                    return self.time

                # if we need to un-decode time to apply the year_offset,
                time_data = self.get_time_undecoded()

            # time has not been decoded
            else:
                time_data = self.time

        if self.year_offset is not None:
            time_data += cftime.date2num(
                datetime(int(self.year_offset), 1, 1),
                units=self.time_attrs['units'],
                calendar=self.time_attrs['calendar'],
            )
        time_out = self.time.copy()
        time_out.data = xr.CFTimeIndex(
            cftime.num2date(
                time_data,
                units=self.time_attrs['units'],
                calendar=self.time_attrs['calendar'],
                only_use_cftime_datetimes=True,
            )
        )
        return time_out 
开发者ID:NCAR,项目名称:esmlab,代码行数:42,代码来源:core.py

示例12: time_year_to_midyeardate

# 需要导入模块: import cftime [as 别名]
# 或者: from cftime import datetime [as 别名]
def time_year_to_midyeardate(self):
        """Set the time coordinate to the mid-point of the year.
        """
        ds = self._ds_time_computed.copy(True)
        ds[self.time_coord_name].data = np.array(
            [cftime.datetime(entry.year, 7, 2) for entry in ds[self.time_coord_name].data]
        )
        return ds 
开发者ID:NCAR,项目名称:esmlab,代码行数:10,代码来源:core.py

示例13: climatology

# 需要导入模块: import cftime [as 别名]
# 或者: from cftime import datetime [as 别名]
def climatology(dset, freq, time_coord_name=None):
    """Compute climatologies for a specified time frequency

    Parameters
    ----------
    dset : xarray.Dataset
           The data on which to operate

    freq : str
        Frequency alias. Accepted alias:

        - ``mon``: for monthly climatologies

    time_coord_name : str
            Name for time coordinate to use


    Returns
    -------
    computed_dset : xarray.Dataset
                    The computed climatology data

    """

    accepted_freq = {'mon'}
    if freq not in accepted_freq:
        raise ValueError(f'{freq} is not among supported frequency aliases={accepted_freq}')

    else:
        ds = dset.esmlab.set_time(time_coord_name=time_coord_name).compute_mon_climatology()
        new_history = f'\n{datetime.now()} esmlab.climatology(<DATASET>, freq="{freq}")'
        ds.attrs['history'] = new_history
        return ds 
开发者ID:NCAR,项目名称:esmlab,代码行数:35,代码来源:core.py

示例14: anomaly

# 需要导入模块: import cftime [as 别名]
# 或者: from cftime import datetime [as 别名]
def anomaly(dset, clim_freq, slice_mon_clim_time=None, time_coord_name=None):
    """Compute anomalies for a specified time frequency

    Parameters
    ----------
    dset : xarray.Dataset
           The data on which to operate

    clim_freq : str
        Climatology frequency alias. Accepted alias:

        - ``mon``: for monthly climatologies

    slice_mon_clim_time : slice, optional
                          a slice object passed to
                          `dset.isel(time=slice_mon_clim_time)` for subseting
                          the time-period overwhich the climatology is computed
    time_coord_name : str
            Name for time coordinate to use


    Returns
    -------
    computed_dset : xarray.Dataset
                    The computed anomaly data

    """

    accepted_freq = {'mon'}
    if clim_freq not in accepted_freq:
        raise ValueError(f'{clim_freq} is not among supported frequency aliases={accepted_freq}')
    else:
        ds = dset.esmlab.set_time(time_coord_name=time_coord_name).compute_mon_anomaly(
            slice_mon_clim_time=slice_mon_clim_time
        )
        new_history = f'\n{datetime.now()} esmlab.anomaly(<DATASET>, clim_freq="{clim_freq}", slice_mon_clim_time="{slice_mon_clim_time}")'
        ds.attrs['history'] = new_history
        return ds 
开发者ID:NCAR,项目名称:esmlab,代码行数:40,代码来源:core.py

示例15: __init__

# 需要导入模块: import cftime [as 别名]
# 或者: from cftime import datetime [as 别名]
def __init__(self, datetime, calendar):
        self.datetime = datetime
        self.calendar = calendar 
开发者ID:SciTools,项目名称:nc-time-axis,代码行数:5,代码来源:__init__.py


注:本文中的cftime.datetime方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。