Make a value with the specified numpy dtype.

    Only datetime64[ns] and datetime64[D] are supported for datetime dtypes.
18985
def coerce_to_dtype(dtype, value):
    
    name = dtype.name
    if name.startswith('datetime64'):
        if name == 'datetime64[D]':
            return make_datetime64D(value)
        elif name == 'datetime64[ns]':
            return make_datetime64ns(value)
        else:
            raise TypeError(
                "Don't know how to coerce values of dtype %s" % dtype
            )
    return dtype.type(value)
287852
def convert_numpy_type(cls, dtype):
        

        m = {
            'int64': cls.DATATYPE_INTEGER64,
            'float64': cls.DATATYPE_FLOAT,
            'object': cls.DATATYPE_TEXT  # Hack. Pandas makes strings into object.
        }

        t = m.get(dtype.name, None)

        if not t:
            raise TypeError(
                "Failed to convert numpy type: '{}' ".format(
                    dtype.name))

        return t
321538
def _setup_dtype(self):
        """"""
        if self._dtype is not None:
            return self._dtype

        dtype = []  # Convert struct data types to numpy data type
        for i, typ in enumerate(self.typlist):
            if typ in self.NUMPY_TYPE_MAP:
                dtype.append(('s' + str(i), self.byteorder +
                              self.NUMPY_TYPE_MAP[typ]))
            else:
                dtype.append(('s' + str(i), 'S' + str(typ)))
        dtype = np.dtype(dtype)
        self._dtype = dtype

        return self._dtype
619136
def np_array_datetime64_compat(arr, *args, **kwargs):
    
    # is_list_like
    if (hasattr(arr, '__iter__') and not isinstance(arr, (str, bytes))):
        arr = [tz_replacer(s) for s in arr]
    else:
        arr = tz_replacer(arr)

    return np.array(arr, *args, **kwargs)
60052
def _create_column(values, dtype):
    ""
    if str(dtype) == "tensor(int64)":
        return numpy.array(values, dtype=numpy.int64)
    elif str(dtype) == "tensor(float)":
        return numpy.array(values, dtype=numpy.float32)
    else:
        raise OnnxRuntimeAssertionError("Unable to create one column from dtype '{0}'".format(dtype))
353556
def coerce_to_target_dtype(self, other):
        

        # if we cannot then coerce to object
        dtype, _ = infer_dtype_from(other, pandas_dtype=True)

        if is_dtype_equal(self.dtype, dtype):
            return self

        if self.is_bool or is_object_dtype(dtype) or is_bool_dtype(dtype):
            # we don't upcast to bool
            return self.astype(object)

        elif ((self.is_float or self.is_complex) and
              (is_integer_dtype(dtype) or is_float_dtype(dtype))):
            # don't coerce float/complex to int
            return self

        elif (self.is_datetime or
              is_datetime64_dtype(dtype) or
              is_datetime64tz_dtype(dtype)):

            # not a datetime
            if not ((is_datetime64_dtype(dtype) or
                     is_datetime64tz_dtype(dtype)) and self.is_datetime):
                return self.astype(object)

            # don't upcast timezone with different timezone or no timezone
            mytz = getattr(self.dtype, 'tz', None)
            othertz = getattr(dtype, 'tz', None)

            if str(mytz) != str(othertz):
                return self.astype(object)

            raise AssertionError("possible recursion in "
                                 "coerce_to_target_dtype: {} {}".format(
                                     self, other))

        elif (self.is_timedelta or is_timedelta64_dtype(dtype)):

            # not a timedelta
            if not (is_timedelta64_dtype(dtype) and self.is_timedelta):
                return self.astype(object)

            raise AssertionError("possible recursion in "
                                 "coerce_to_target_dtype: {} {}".format(
                                     self, other))

        try:
            return self.astype(dtype)
        except (ValueError, TypeError, OverflowError):
            pass

        return self.astype(object)
691996
def pandas_dtype(dtype):
    
    # short-circuit
    if isinstance(dtype, np.ndarray):
        return dtype.dtype
    elif isinstance(dtype, (np.dtype, PandasExtensionDtype, ExtensionDtype)):
        return dtype

    # registered extension types
    result = registry.find(dtype)
    if result is not None:
        return result

    # try a numpy dtype
    # raise a consistent TypeError if failed
    try:
        npdtype = np.dtype(dtype)
    except Exception:
        # we don't want to force a repr of the non-string
        if not isinstance(dtype, str):
            raise TypeError("data type not understood")
        raise TypeError("data type '{}' not understood".format(
            dtype))

    # Any invalid dtype (such as pd.Timestamp) should raise an error.
    # np.dtype(invalid_type).kind = 0 for such objects. However, this will
    # also catch some valid dtypes such as object, np.object_ and 'object'
    # which we safeguard against by catching them earlier and returning
    # np.dtype(valid_dtype) before this condition is evaluated.
    if is_hashable(dtype) and dtype in [object, np.object_, 'object', 'O']:
        # check hashability to avoid errors/DeprecationWarning when we get
        # here and `dtype` is an array
        return npdtype
    elif npdtype.kind == 'O':
        raise TypeError("dtype '{}' not understood".format(dtype))

    return npdtype
1125223
def to_native_types(self, slicer=None, na_rep=None, date_format=None,
                        quoting=None, **kwargs):
        

        values = self.values
        i8values = self.values.view('i8')

        if slicer is not None:
            values = values[..., slicer]
            i8values = i8values[..., slicer]

        from pandas.io.formats.format import _get_format_datetime64_from_values
        fmt = _get_format_datetime64_from_values(values, date_format)

        result = tslib.format_array_from_datetime(
            i8values.ravel(), tz=getattr(self.values, 'tz', None),
            format=fmt, na_rep=na_rep).reshape(i8values.shape)
        return np.atleast_2d(result)
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
5750
def _serialize(self, value, attr, obj, **kwargs):
        """"""
        if value is None:
            return None

        return int(datetime_to_timestamp(value))
1158753
def _try_cast_result(self, result, dtype=None):
        
        if dtype is None:
            dtype = self.dtype

        if self.is_integer or self.is_bool or self.is_datetime:
            pass
        elif self.is_float and result.dtype == self.dtype:

            # protect against a bool/object showing up here
            if isinstance(dtype, str) and dtype == 'infer':
                return result
            if not isinstance(dtype, type):
                dtype = dtype.type
            if issubclass(dtype, (np.bool_, np.object_)):
                if issubclass(dtype, np.bool_):
                    if isna(result).all():
                        return result.astype(np.bool_)
                    else:
                        result = result.astype(np.object_)
                        result[result == 1] = True
                        result[result == 0] = False
                        return result
                else:
                    return result.astype(np.object_)

            return result

        # may need to change the dtype here
        return maybe_downcast_to_dtype(result, dtype)
542087
def data_type_to_numpy(datatype, unsigned=False):
    """"""
    basic_type = _dtypeLookup[datatype]

    if datatype in (stream.STRING, stream.OPAQUE):
        return np.dtype(basic_type)

    if unsigned:
        basic_type = basic_type.replace('i', 'u')
    return np.dtype('=' + basic_type)
1254793
def cast_datetime_filter(value):
    
    if isinstance(value, str):
        dtime = parse_datetime(value)

    elif isinstance(value, datetime):
        dtime = value
    else:
        raise ValueError('Received value of type {0}'.format(type(value)))

    return dtime.isoformat()
1052236
def python_value(self, dtype, dvalue):
        """"""
        try:
            return CONVERTERS[dtype](dvalue)
        except KeyError:
            if dtype == clips.common.CLIPSType.MULTIFIELD:
                return self.multifield_to_list()
            if dtype == clips.common.CLIPSType.FACT_ADDRESS:
                return clips.facts.new_fact(self._env, lib.to_pointer(dvalue))
            if dtype == clips.common.CLIPSType.INSTANCE_ADDRESS:
                return clips.classes.Instance(self._env, lib.to_pointer(dvalue))

        return None
1033079
def is_np_datetime_like(dtype: Union[str, np.dtype]) -> bool:
    
    return (np.issubdtype(dtype, np.datetime64) or
            np.issubdtype(dtype, np.timedelta64))
747003
def values(self, dtype, dates, sids):
        
        shape = (len(dates), len(sids))
        return {
            datetime64ns_dtype: self._datetime_values,
            float64_dtype: self._float_values,
            int64_dtype: self._int_values,
            bool_dtype: self._bool_values,
            object_dtype: self._object_values,
        }[dtype](shape)
173017
def _sub_datetime_arraylike(self, other):
        """"""
        if len(self) != len(other):
            raise ValueError("cannot add indices of unequal length")

        if isinstance(other, np.ndarray):
            assert is_datetime64_dtype(other)
            other = type(self)(other)

        if not self._has_same_tz(other):
            # require tz compat
            raise TypeError("{cls} subtraction must have the same "
                            "timezones or no timezones"
                            .format(cls=type(self).__name__))

        self_i8 = self.asi8
        other_i8 = other.asi8
        arr_mask = self._isnan | other._isnan
        new_values = checked_add_with_arr(self_i8, -other_i8,
                                          arr_mask=arr_mask)
        if self._hasnans or other._hasnans:
            new_values[arr_mask] = iNaT
        return new_values.view('timedelta64[ns]')