Safely converts NumPy datetime64 to a datetime object.
186636
def dt64_to_dt(dt64):
    
    ts = (dt64 - np.datetime64('1970-01-01T00:00:00')) / np.timedelta64(1, 's')
    return dt.datetime.utcfromtimestamp(ts)
596840
def _coerce_to_type(x):
    
    dtype = None

    if is_datetime64tz_dtype(x):
        dtype = x.dtype
    elif is_datetime64_dtype(x):
        x = to_datetime(x)
        dtype = np.dtype('datetime64[ns]')
    elif is_timedelta64_dtype(x):
        x = to_timedelta(x)
        dtype = np.dtype('timedelta64[ns]')

    if dtype is not None:
        # GH 19768: force NaT to NaN during integer conversion
        x = np.where(x.notna(), x.view(np.int64), np.nan)

    return x, dtype
163629
def to_datetime(plain_date, hours=0, minutes=0, seconds=0, ms=0):
    """"""
    # don't mess with datetimes
    if isinstance(plain_date, datetime.datetime):
        return plain_date
    return datetime.datetime(
        plain_date.year,
        plain_date.month,
        plain_date.day,
        hours,
        minutes,
        seconds,
        ms,
    )
107352
def _try_cast(self, result, obj, numeric_only=False):
        
        if obj.ndim > 1:
            dtype = obj._values.dtype
        else:
            dtype = obj.dtype

        if not is_scalar(result):
            if is_datetime64tz_dtype(dtype):
                # GH 23683
                # Prior results _may_ have been generated in UTC.
                # Ensure we localize to UTC first before converting
                # to the target timezone
                try:
                    result = obj._values._from_sequence(
                        result, dtype='datetime64[ns, UTC]'
                    )
                    result = result.astype(dtype)
                except TypeError:
                    # _try_cast was called at a point where the result
                    # was already tz-aware
                    pass
            elif is_extension_array_dtype(dtype):
                # The function can return something of any type, so check
                # if the type is compatible with the calling EA.
                try:
                    result = obj._values._from_sequence(result, dtype=dtype)
                except Exception:
                    # https://github.com/pandas-dev/pandas/issues/22850
                    # pandas has no control over what 3rd-party ExtensionArrays
                    # do in _values_from_sequence. We still want ops to work
                    # though, so we catch any regular Exception.
                    pass
            elif numeric_only and is_numeric_dtype(dtype) or not numeric_only:
                result = maybe_downcast_to_dtype(result, dtype)

        return 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
1218597
def _make_datetime(s):
    """
    s = bytearray(s)  # For Python 2
    year, month, day, hour, minute, second, cs = s
    if year < 70:
        year += 100
    return datetime(1900 + year, month, day, hour, minute, second, 10000 * cs)
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)
313923
def _add_datetime_arraylike(self, other):
        
        if isinstance(other, np.ndarray):
            # At this point we have already checked that dtype is datetime64
            from pandas.core.arrays import DatetimeArray
            other = DatetimeArray(other)

        # defer to implementation in DatetimeArray
        return other + self
1205671
def _convert_to_datetime(unix_timestamp):
    '''
    
    '''
    try:
        unix_timestamp = float(unix_timestamp)
        return datetime.fromtimestamp(unix_timestamp).strftime('%Y-%m-%d %H:%M:%S')
    except (ValueError, TypeError):
        return 'Invalid Timestamp'
37454
private DateTime[] asDateTime( List<Object> values ) {
        ValueFactory<DateTime> factory = valueFactories.getDateFactory();
        DateTime[] res = new DateTime[values.size()];
        for (int i = 0; i < res.length; i++) {
            res[i] = factory.create(((GregorianCalendar)values.get(i)).getTime());
        }
        return res;
    }
534214
def soft_convert_objects(values, datetime=True, numeric=True, timedelta=True,
                         coerce=False, copy=True):
    

    conversion_count = sum((datetime, numeric, timedelta))
    if conversion_count == 0:
        raise ValueError('At least one of datetime, numeric or timedelta must '
                         'be True.')
    elif conversion_count > 1 and coerce:
        raise ValueError("Only one of 'datetime', 'numeric' or "
                         "'timedelta' can be True when when coerce=True.")

    if isinstance(values, (list, tuple)):
        # List or scalar
        values = np.array(values, dtype=np.object_)
    elif not hasattr(values, 'dtype'):
        values = np.array([values], dtype=np.object_)
    elif not is_object_dtype(values.dtype):
        # If not object, do not attempt conversion
        values = values.copy() if copy else values
        return values

    # If 1 flag is coerce, ensure 2 others are False
    if coerce:
        # Immediate return if coerce
        if datetime:
            from pandas import to_datetime
            return to_datetime(values, errors='coerce').to_numpy()
        elif timedelta:
            from pandas import to_timedelta
            return to_timedelta(values, errors='coerce').to_numpy()
        elif numeric:
            from pandas import to_numeric
            return to_numeric(values, errors='coerce')

    # Soft conversions
    if datetime:
        # GH 20380, when datetime is beyond year 2262, hence outside
        # bound of nanosecond-resolution 64-bit integers.
        try:
            values = lib.maybe_convert_objects(values,
                                               convert_datetime=datetime)
        except OutOfBoundsDatetime:
            pass

    if timedelta and is_object_dtype(values.dtype):
        # Object check to ensure only run if previous did not convert
        values = lib.maybe_convert_objects(values, convert_timedelta=timedelta)

    if numeric and is_object_dtype(values.dtype):
        try:
            converted = lib.maybe_convert_numeric(values, set(),
                                                  coerce_numeric=True)
            # If all NaNs, then do not-alter
            values = converted if not isna(converted).all() else values
            values = values.copy() if copy else values
        except Exception:
            pass

    return values
658309
def is_datetime_like(dtype):
    
    return (np.issubdtype(dtype, np.datetime64) or
            np.issubdtype(dtype, np.timedelta64))
1359131
def cast_datetime(ts, fmt=None):
    """"""
    dt = datetime.datetime.fromtimestamp(ts)
    if fmt:
        return dt.strftime(fmt)
    return dt
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
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
399668
def string_to_datetime(self, obj):
        
        if isinstance(obj, six.string_types) and len(obj) == 19:
            try:
                return datetime.strptime(obj, "%Y-%m-%dT%H:%M:%S")
            except ValueError:
                pass
        if isinstance(obj, six.string_types) and len(obj) > 19:
            try:
                return datetime.strptime(obj, "%Y-%m-%dT%H:%M:%S.%f")
            except ValueError:
                pass
        if isinstance(obj, six.string_types) and len(obj) == 10:
            try:
                return datetime.strptime(obj, "%Y-%m-%d")
            except ValueError:
                pass
        return obj
1375046
def Datetime(null=True, **kwargs):
    """"""
    return Property(
        types=datetime.datetime,
        convert=util.local_timezone,
        load=dateutil.parser.parse,
        null=null,
        **kwargs
    )