Given an array of cftime.datetime objects, return an array of
    numpy.datetime64 objects of the same size
486120
def cftime_to_nptime(times):
    """"""
    times = np.asarray(times)
    new = np.empty(times.shape, dtype='M8[ns]')
    for i, t in np.ndenumerate(times):
        try:
            # Use pandas.Timestamp in place of datetime.datetime, because
            # NumPy casts it safely it np.datetime64[ns] for dates outside
            # 1678 to 2262 (this is not currently the case for
            # datetime.datetime).
            dt = pd.Timestamp(t.year, t.month, t.day, t.hour, t.minute,
                              t.second, t.microsecond)
        except ValueError as e:
            raise ValueError('Cannot convert date {} to a date in the '
                             'standard calendar.  Reason: {}.'.format(t, e))
        new[i] = np.datetime64(dt)
    return new
855003
def rnd_datetime_array(self,
                           size, start=datetime(1970, 1, 1), end=datetime.now()):
        
        if isinstance(start, string_types):
            start = self.str2datetime(start)
        if isinstance(end, str):
            end = self.str2datetime(end)
        if start > end:
            raise ValueError("start time has to be earlier than end time")

        return self.randn(size, self._rnd_datetime, start, end)
312855
def datetime_from_timestamp(n, epoch=datetime.datetime.fromordinal(693594)):
    
    return epoch + datetime.timedelta(n)
1033079
def is_np_datetime_like(dtype: Union[str, np.dtype]) -> bool:
    
    return (np.issubdtype(dtype, np.datetime64) or
            np.issubdtype(dtype, np.timedelta64))
877575
def load
      ArrayConverters.load(self)
      BooleanConverters.load(self)
      DateTimeConverters.load(self)
      NumericConverters.load(self)
      RangeConverters.load(self)
    end
625176
def to_ut1unix(time: Union[str, datetime, float, np.ndarray]) -> np.ndarray:
    
    # keep this order
    time = totime(time)

    if isinstance(time, (float, int)):
        return time

    if isinstance(time, (tuple, list, np.ndarray)):
        assert isinstance(time[0], datetime), f'expected datetime, not {type(time[0])}'
        return np.array(list(map(dt2ut1, time)))
    else:
        assert isinstance(time, datetime)
        return dt2ut1(time)
163914
def find_common_type(types):
    

    if len(types) == 0:
        raise ValueError('no types given')

    first = types[0]

    # workaround for find_common_type([np.dtype('datetime64[ns]')] * 2)
    # => object
    if all(is_dtype_equal(first, t) for t in types[1:]):
        return first

    if any(isinstance(t, (PandasExtensionDtype, ExtensionDtype))
           for t in types):
        return np.object

    # take lowest unit
    if all(is_datetime64_dtype(t) for t in types):
        return np.dtype('datetime64[ns]')
    if all(is_timedelta64_dtype(t) for t in types):
        return np.dtype('timedelta64[ns]')

    # don't mix bool / int or float or complex
    # this is different from numpy, which casts bool with float/int as int
    has_bools = any(is_bool_dtype(t) for t in types)
    if has_bools:
        for t in types:
            if is_integer_dtype(t) or is_float_dtype(t) or is_complex_dtype(t):
                return np.object

    return np.find_common_type(types, [])
131800
def _decode_datetime(obj):
    """"""

    if '__datetime__' in obj:
        obj = datetime.datetime.strptime(obj['as_str'].decode(), "%Y%m%dT%H:%M:%S.%f")
    return obj
1265640
def _ensure_plottable(*args):
    
    numpy_types = [np.floating, np.integer, np.timedelta64, np.datetime64]
    other_types = [datetime]
    try:
        import cftime
        cftime_datetime = [cftime.datetime]
    except ImportError:
        cftime_datetime = []
    other_types = other_types + cftime_datetime
    for x in args:
        if not (_valid_numpy_subdtype(np.array(x), numpy_types)
                or _valid_other_type(np.array(x), other_types)):
            raise TypeError('Plotting requires coordinates to be numeric '
                            'or dates of type np.datetime64, '
                            'datetime.datetime, cftime.datetime or '
                            'pd.Interval.')
        if (_valid_other_type(np.array(x), cftime_datetime)
                and not nc_time_axis_available):
            raise ImportError('Plotting of arrays of cftime.datetime '
                              'objects or arrays indexed by '
                              'cftime.datetime objects requires the '
                              'optional `nc-time-axis` (v1.2.0 or later) '
                              'package.')
239107
def datetime2gtd(time: Union[str, datetime.datetime, np.datetime64],
                 glon: Union[float, List[float], np.ndarray] = np.nan) -> Tuple[int, float, float]:
    
# %%
    T = np.atleast_1d(time)
    glon = np.asarray(glon)
    doy = np.empty_like(T, int)
    utsec = np.empty_like(T, float)
    stl = np.empty((T.size, *glon.shape))

    for i, t in enumerate(T):
        if isinstance(t, str):
            t = parse(t)
        elif isinstance(t, np.datetime64):
            t = t.astype(datetime.datetime)
        elif isinstance(t, (datetime.datetime, datetime.date)):
            pass
        else:
            raise TypeError('unknown time datatype {}'.format(type(t)))
# %% Day of year
        doy[i] = int(t.strftime('%j'))
# %% seconds since utc midnight
        utsec[i] = datetime2utsec(t)

        stl[i, ...] = utsec[i] / 3600. + glon / 15.

    return doy, utsec, stl
381704
def array(arr, *args, **kwargs):
    '''
    
    '''
    return weldarray(np.array(arr, *args, **kwargs))
1041036
def _encode_datetime_with_cftime(dates, units, calendar):
    
    cftime = _import_cftime()

    if np.issubdtype(dates.dtype, np.datetime64):
        # numpy's broken datetime conversion only works for us precision
        dates = dates.astype('M8[us]').astype(datetime)

    def encode_datetime(d):
        return np.nan if d is None else cftime.date2num(d, units, calendar)

    return np.vectorize(encode_datetime)(dates)
336181
def np_to_datetime(intime):
    """"""
    nptime = np.atleast_1d(intime)
    np_corr = (nptime - np.datetime64('1970-01-01T00:00:00')) / \
        np.timedelta64(1, 's')
    return [datetime.utcfromtimestamp(t) for t in np_corr]
238341
def mean(array, axis=None, skipna=None, **kwargs):
    """"""
    from .common import _contains_cftime_datetimes

    array = asarray(array)
    if array.dtype.kind in 'Mm':
        offset = min(array)
        # xarray always uses np.datetime64[ns] for np.datetime64 data
        dtype = 'timedelta64[ns]'
        return _mean(datetime_to_numeric(array, offset), axis=axis,
                     skipna=skipna, **kwargs).astype(dtype) + offset
    elif _contains_cftime_datetimes(array):
        if isinstance(array, dask_array_type):
            raise NotImplementedError(
                'Computing the mean of an array containing '
                'cftime.datetime objects is not yet implemented on '
                'dask arrays.')
        offset = min(array)
        timedeltas = datetime_to_numeric(array, offset, datetime_unit='us')
        mean_timedeltas = _mean(timedeltas, axis=axis, skipna=skipna,
                                **kwargs)
        return _to_pytimedelta(mean_timedeltas, unit='us') + offset
    else:
        return _mean(array, axis=axis, skipna=skipna, **kwargs)
1326992
def _reduce_datetimes(row):
    """"""

    row = list(row)

    for i in range(len(row)):
        if hasattr(row[i], 'isoformat'):
            row[i] = row[i].isoformat()
    return tuple(row)
27828
def convert_datetime_type(obj):
    ''' 

    '''
    # Pandas NaT
    if pd and obj is pd.NaT:
        return np.nan

    # Pandas Period
    if pd and isinstance(obj, pd.Period):
        return obj.to_timestamp().value / 10**6.0

    # Pandas Timestamp
    if pd and isinstance(obj, _pd_timestamp): return obj.value / 10**6.0

    # Pandas Timedelta
    elif pd and isinstance(obj, pd.Timedelta): return obj.value / 10**6.0

    # Datetime (datetime is a subclass of date)
    elif isinstance(obj, dt.datetime):
        diff = obj.replace(tzinfo=None) - DT_EPOCH
        return diff.total_seconds() * 1000.

    # Date
    elif isinstance(obj, dt.date):
        return (dt.datetime(*obj.timetuple()[:6]) - DT_EPOCH).total_seconds() * 1000

    # NumPy datetime64
    elif isinstance(obj, np.datetime64):
        epoch_delta = obj - NP_EPOCH
        return (epoch_delta / NP_MS_DELTA)

    # Time
    elif isinstance(obj, dt.time):
        return (obj.hour * 3600 + obj.minute * 60 + obj.second) * 1000 + obj.microsecond / 1000.
25425
def _dtype_array(self):
        """"""
        attrtype = []
        attrdiff = []

        for key in self._headers:
            if self.attr[key][0] == 'continuous':
                attrtype.append(1)
            else:
                attrtype.append(0)
            attrdiff.append(self.attr[key][3])

        attrtype = np.array(attrtype)
        cidx = np.where(attrtype == 1)[0]
        didx = np.where(attrtype == 0)[0]

        attrdiff = np.array(attrdiff)

        return attrdiff, cidx, didx