Ejemplo n.º 1
0
    def _generate(cls, start, end, periods, name, offset,
                  tz=None, normalize=False):
        _normalized = True

        if start is not None:
            start = Timestamp(start)
            if not isinstance(start, Timestamp):
                raise ValueError('Failed to convert %s to timestamp'
                                 % start)

            if normalize:
                start = normalize_date(start)
                _normalized = True
            else:
                _normalized = _normalized and start.time() == _midnight

        if end is not None:
            end = Timestamp(end)
            if not isinstance(end, Timestamp):
                raise ValueError('Failed to convert %s to timestamp'
                                 % end)

            if normalize:
                end = normalize_date(end)
                _normalized = True
            else:
                _normalized = _normalized and end.time() == _midnight

        start, end, tz = tools._figure_out_timezone(start, end, tz)

        if (offset._should_cache() and
            not (offset._normalize_cache and not _normalized) and
            _naive_in_cache_range(start, end)):
            index = cls._cached_range(start, end, periods=periods,
                                      offset=offset, name=name)
        else:
            index = _generate_regular_range(start, end, periods, offset)

        if tz is not None:
            # Convert local to UTC
            ints = index.view('i8')
            lib.tz_localize_check(ints, tz)
            index = lib.tz_convert(ints, tz, _utc())
            index = index.view('M8[ns]')

        index = index.view(cls)
        index.name = name
        index.offset = offset
        index.tz = tz

        return index
Ejemplo n.º 2
0
    def tz_localize(self, tz):
        """
        Localize tz-naive DatetimeIndex to given time zone (using pytz)

        Returns
        -------
        localized : DatetimeIndex
        """
        if self.tz is not None:
            raise ValueError("Already have timezone info, "
                             "use tz_convert to convert.")
        tz = tools._maybe_get_tz(tz)

        lib.tz_localize_check(self.asi8, tz)

        # Convert to UTC
        new_dates = lib.tz_convert(self.asi8, tz, _utc())
        new_dates = new_dates.view('M8[ns]')
        return self._simple_new(new_dates, self.name, self.offset, tz)
Ejemplo n.º 3
0
    def tz_validate(self):
        """
        For a localized time zone, verify that there are no DST ambiguities
        (using pytz)

        Returns
        -------
        result : boolean
            True if there are no DST ambiguities
        """
        import pytz

        if self.tz is None or self.tz is pytz.utc:
            return True

        # See if there are any DST resolution problems
        try:
            lib.tz_localize_check(self.asi8, self.tz)
        except:
            return False

        return True
Ejemplo n.º 4
0
    def tz_validate(self):
        """
        For a localized time zone, verify that there are no DST ambiguities
        (using pytz)

        Returns
        -------
        result : boolean
            True if there are no DST ambiguities
        """
        import pytz

        if self.tz is None or self.tz is pytz.utc:
            return True

        # See if there are any DST resolution problems
        try:
            lib.tz_localize_check(self.asi8, self.tz)
        except:
            return False

        return True
Ejemplo n.º 5
0
    def __new__(cls, data=None,
                freq=None, start=None, end=None, periods=None,
                copy=False, name=None, tz=None,
                verify_integrity=True, normalize=False, **kwds):

        warn = False
        if 'offset' in kwds and kwds['offset']:
            freq = kwds['offset']
            warn = True

        infer_freq = False
        if not isinstance(freq, DateOffset):
            if freq != 'infer':
                freq = to_offset(freq)
            else:
                infer_freq = True
                freq = None

        if warn:
            import warnings
            warnings.warn("parameter 'offset' is deprecated, "
                          "please use 'freq' instead",
                          FutureWarning)
            if isinstance(freq, basestring):
                freq = to_offset(freq)
        else:
            if isinstance(freq, basestring):
                freq = to_offset(freq)

        offset = freq

        if data is None and offset is None:
            raise ValueError("Must provide freq argument if no data is "
                             "supplied")

        if data is None:
            return cls._generate(start, end, periods, name, offset,
                                 tz=tz, normalize=normalize)

        if not isinstance(data, np.ndarray):
            if np.isscalar(data):
                raise ValueError('DatetimeIndex() must be called with a '
                                 'collection of some kind, %s was passed'
                                 % repr(data))

            if isinstance(data, datetime):
                data = [data]

            # other iterable of some kind
            if not isinstance(data, (list, tuple)):
                data = list(data)

            data = np.asarray(data, dtype='O')

            # try a few ways to make it datetime64
            if lib.is_string_array(data):
                data = _str_to_dt_array(data, offset)
            else:
                data = tools.to_datetime(data)
                data.offset = offset

        if issubclass(data.dtype.type, basestring):
            subarr = _str_to_dt_array(data, offset)
        elif issubclass(data.dtype.type, np.datetime64):
            if isinstance(data, DatetimeIndex):
                subarr = data.values
                offset = data.offset
                verify_integrity = False
            else:
                subarr = np.array(data, dtype='M8[ns]', copy=copy)
        elif issubclass(data.dtype.type, np.integer):
            subarr = np.array(data, dtype='M8[ns]', copy=copy)
        else:
            subarr = tools.to_datetime(data)
            if not np.issubdtype(subarr.dtype, np.datetime64):
                raise TypeError('Unable to convert %s to datetime dtype'
                                % str(data))

        if tz is not None:
            tz = tools._maybe_get_tz(tz)
            # Convert local to UTC
            ints = subarr.view('i8')
            lib.tz_localize_check(ints, tz)
            subarr = lib.tz_convert(ints, tz, _utc())
            subarr = subarr.view('M8[ns]')

        subarr = subarr.view(cls)
        subarr.name = name
        subarr.offset = offset
        subarr.tz = tz

        if verify_integrity and len(subarr) > 0:
            if offset is not None and not infer_freq:
                inferred = subarr.inferred_freq
                if inferred != offset.freqstr:
                    raise ValueError('Dates do not conform to passed '
                                     'frequency')

        if infer_freq:
            inferred = subarr.inferred_freq
            if inferred:
                subarr.offset = to_offset(inferred)

        return subarr