當前位置: 首頁>>代碼示例>>Python>>正文


Python datetimes.parse_time_string方法代碼示例

本文整理匯總了Python中pandas.core.tools.datetimes.parse_time_string方法的典型用法代碼示例。如果您正苦於以下問題:Python datetimes.parse_time_string方法的具體用法?Python datetimes.parse_time_string怎麽用?Python datetimes.parse_time_string使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在pandas.core.tools.datetimes的用法示例。


在下文中一共展示了datetimes.parse_time_string方法的14個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: test_parsers_timestring

# 需要導入模塊: from pandas.core.tools import datetimes [as 別名]
# 或者: from pandas.core.tools.datetimes import parse_time_string [as 別名]
def test_parsers_timestring(self):
        # must be the same as dateutil result
        cases = {'10:15': (parse('10:15'), datetime(1, 1, 1, 10, 15)),
                 '9:05': (parse('9:05'), datetime(1, 1, 1, 9, 5))}

        for date_str, (exp_now, exp_def) in compat.iteritems(cases):
            result1, _, _ = tools.parse_time_string(date_str)
            result2 = to_datetime(date_str)
            result3 = to_datetime([date_str])
            result4 = Timestamp(date_str)
            result5 = DatetimeIndex([date_str])[0]
            # parse time string return time string based on default date
            # others are not, and can't be changed because it is used in
            # time series plot
            assert result1 == exp_def
            assert result2 == exp_now
            assert result3 == exp_now
            assert result4 == exp_now
            assert result5 == exp_now 
開發者ID:securityclippy,項目名稱:elasticintel,代碼行數:21,代碼來源:test_tools.py

示例2: test_parsers_quarterly_with_freq

# 需要導入模塊: from pandas.core.tools import datetimes [as 別名]
# 或者: from pandas.core.tools.datetimes import parse_time_string [as 別名]
def test_parsers_quarterly_with_freq(self):
        msg = ('Incorrect quarterly string is given, quarter '
               'must be between 1 and 4: 2013Q5')
        with tm.assert_raises_regex(parsing.DateParseError, msg):
            tools.parse_time_string('2013Q5')

        # GH 5418
        msg = ('Unable to retrieve month information from given freq: '
               'INVLD-L-DEC-SAT')
        with tm.assert_raises_regex(parsing.DateParseError, msg):
            tools.parse_time_string('2013Q1', freq='INVLD-L-DEC-SAT')

        cases = {('2013Q2', None): datetime(2013, 4, 1),
                 ('2013Q2', 'A-APR'): datetime(2012, 8, 1),
                 ('2013-Q2', 'A-DEC'): datetime(2013, 4, 1)}

        for (date_str, freq), exp in compat.iteritems(cases):
            result, _, _ = tools.parse_time_string(date_str, freq=freq)
            assert result == exp 
開發者ID:securityclippy,項目名稱:elasticintel,代碼行數:21,代碼來源:test_tools.py

示例3: get_loc

# 需要導入模塊: from pandas.core.tools import datetimes [as 別名]
# 或者: from pandas.core.tools.datetimes import parse_time_string [as 別名]
def get_loc(self, key, method=None, tolerance=None):
        """
        Get integer location for requested label

        Returns
        -------
        loc : int
        """
        try:
            return self._engine.get_loc(key)
        except KeyError:
            if is_integer(key):
                raise

            try:
                asdt, parsed, reso = parse_time_string(key, self.freq)
                key = asdt
            except TypeError:
                pass
            except DateParseError:
                # A string with invalid format
                raise KeyError("Cannot interpret '{}' as period".format(key))

            try:
                key = Period(key, freq=self.freq)
            except ValueError:
                # we cannot construct the Period
                # as we have an invalid type
                raise KeyError(key)

            try:
                ordinal = iNaT if key is NaT else key.ordinal
                if tolerance is not None:
                    tolerance = self._convert_tolerance(tolerance,
                                                        np.asarray(key))
                return self._int64index.get_loc(ordinal, method, tolerance)

            except KeyError:
                raise KeyError(key) 
開發者ID:Frank-qlu,項目名稱:recruit,代碼行數:41,代碼來源:period.py

示例4: _maybe_cast_slice_bound

# 需要導入模塊: from pandas.core.tools import datetimes [as 別名]
# 或者: from pandas.core.tools.datetimes import parse_time_string [as 別名]
def _maybe_cast_slice_bound(self, label, side, kind):
        """
        If label is a string or a datetime, cast it to Period.ordinal according
        to resolution.

        Parameters
        ----------
        label : object
        side : {'left', 'right'}
        kind : {'ix', 'loc', 'getitem'}

        Returns
        -------
        bound : Period or object

        Notes
        -----
        Value of `side` parameter should be validated in caller.

        """
        assert kind in ['ix', 'loc', 'getitem']

        if isinstance(label, datetime):
            return Period(label, freq=self.freq)
        elif isinstance(label, compat.string_types):
            try:
                _, parsed, reso = parse_time_string(label, self.freq)
                bounds = self._parsed_string_to_bounds(reso, parsed)
                return bounds[0 if side == 'left' else 1]
            except Exception:
                raise KeyError(label)
        elif is_integer(label) or is_float(label):
            self._invalid_indexer('slice', label)

        return label 
開發者ID:Frank-qlu,項目名稱:recruit,代碼行數:37,代碼來源:period.py

示例5: _get_string_slice

# 需要導入模塊: from pandas.core.tools import datetimes [as 別名]
# 或者: from pandas.core.tools.datetimes import parse_time_string [as 別名]
def _get_string_slice(self, key):
        if not self.is_monotonic:
            raise ValueError('Partial indexing only valid for '
                             'ordered time series')

        key, parsed, reso = parse_time_string(key, self.freq)
        grp = resolution.Resolution.get_freq_group(reso)
        freqn = resolution.get_freq_group(self.freq)
        if reso in ['day', 'hour', 'minute', 'second'] and not grp < freqn:
            raise KeyError(key)

        t1, t2 = self._parsed_string_to_bounds(reso, parsed)
        return slice(self.searchsorted(t1.ordinal, side='left'),
                     self.searchsorted(t2.ordinal, side='right')) 
開發者ID:Frank-qlu,項目名稱:recruit,代碼行數:16,代碼來源:period.py

示例6: get_loc

# 需要導入模塊: from pandas.core.tools import datetimes [as 別名]
# 或者: from pandas.core.tools.datetimes import parse_time_string [as 別名]
def get_loc(self, key, method=None, tolerance=None):
        """
        Get integer location for requested label

        Returns
        -------
        loc : int
        """
        try:
            return self._engine.get_loc(key)
        except KeyError:
            if is_integer(key):
                raise

            try:
                asdt, parsed, reso = parse_time_string(key, self.freq)
                key = asdt
            except TypeError:
                pass

            try:
                key = Period(key, freq=self.freq)
            except ValueError:
                # we cannot construct the Period
                # as we have an invalid type
                raise KeyError(key)

            try:
                ordinal = tslib.iNaT if key is tslib.NaT else key.ordinal
                if tolerance is not None:
                    tolerance = self._convert_tolerance(tolerance,
                                                        np.asarray(key))
                return self._int64index.get_loc(ordinal, method, tolerance)

            except KeyError:
                raise KeyError(key) 
開發者ID:birforce,項目名稱:vnpy_crypto,代碼行數:38,代碼來源:period.py

示例7: _get_string_slice

# 需要導入模塊: from pandas.core.tools import datetimes [as 別名]
# 或者: from pandas.core.tools.datetimes import parse_time_string [as 別名]
def _get_string_slice(self, key):
        if not self.is_monotonic:
            raise ValueError('Partial indexing only valid for '
                             'ordered time series')

        key, parsed, reso = parse_time_string(key, self.freq)
        grp = frequencies.Resolution.get_freq_group(reso)
        freqn = frequencies.get_freq_group(self.freq)
        if reso in ['day', 'hour', 'minute', 'second'] and not grp < freqn:
            raise KeyError(key)

        t1, t2 = self._parsed_string_to_bounds(reso, parsed)
        return slice(self.searchsorted(t1.ordinal, side='left'),
                     self.searchsorted(t2.ordinal, side='right')) 
開發者ID:nccgroup,項目名稱:Splunking-Crime,代碼行數:16,代碼來源:period.py

示例8: _check_timestep_init

# 需要導入模塊: from pandas.core.tools import datetimes [as 別名]
# 或者: from pandas.core.tools.datetimes import parse_time_string [as 別名]
def _check_timestep_init(self):
        try:
            float(self.timestep_init)
        except ValueError:
            try:
                parse_time_string(self.timestep_init, dayfirst=True)
            except ValueError:
                raise LisfloodError('Option timestepInit was not parsable. Must be integer or date string: {}'.format(self.timestep_init))
            else:
                return True
        else:
            return True 
開發者ID:ec-jrc,項目名稱:lisflood-code,代碼行數:14,代碼來源:settings.py

示例9: calendar

# 需要導入模塊: from pandas.core.tools import datetimes [as 別名]
# 或者: from pandas.core.tools.datetimes import parse_time_string [as 別名]
def calendar(date_in, calendar_type='proleptic_gregorian'):
    """ Get date or number of steps from input.

    Get date from input string using one of the available formats or get time step number from input number or string.
    Used to get the date from CalendarDayStart (input) in the settings xml

    :param date_in: string containing a date in one of the available formats or time step number as number or string
    :param calendar_type:
    :rtype: datetime object or float number
    :returns: date as datetime or time step number as float
    :raises ValueError: stop if input is not a step number AND it is in wrong date format
    """
    try:
        # try reading step number from number or string
        return float(date_in)
    except ValueError:
        # try reading a date in one of available formats
        try:
            _t_units = "hours since 1970-01-01 00:00:00"  # units used for date type conversion (datetime.datetime -> calendar-specific if needed)
            date = parse_time_string(date_in, dayfirst=True)[0]  # datetime.datetime type
            step = date2num(date, _t_units, calendar_type)  # float type
            return num2date(step, _t_units, calendar_type)  # calendar-dependent type from netCDF4.netcdftime._netcdftime module
        except:
            # if cannot read input then stop
            msg = "Wrong step or date format in XML settings file\n Input {}".format(date_in)
            raise LisfloodError(msg) 
開發者ID:ec-jrc,項目名稱:lisflood-code,代碼行數:28,代碼來源:settings.py

示例10: test_parsers_quarter_invalid

# 需要導入模塊: from pandas.core.tools import datetimes [as 別名]
# 或者: from pandas.core.tools.datetimes import parse_time_string [as 別名]
def test_parsers_quarter_invalid(self):

        cases = ['2Q 2005', '2Q-200A', '2Q-200', '22Q2005', '6Q-20', '2Q200.']
        for case in cases:
            pytest.raises(ValueError, tools.parse_time_string, case) 
開發者ID:securityclippy,項目名稱:elasticintel,代碼行數:7,代碼來源:test_tools.py

示例11: test_parsers_monthfreq

# 需要導入模塊: from pandas.core.tools import datetimes [as 別名]
# 或者: from pandas.core.tools.datetimes import parse_time_string [as 別名]
def test_parsers_monthfreq(self):
        cases = {'201101': datetime(2011, 1, 1, 0, 0),
                 '200005': datetime(2000, 5, 1, 0, 0)}

        for date_str, expected in compat.iteritems(cases):
            result1, _, _ = tools.parse_time_string(date_str, freq='M')
            assert result1 == expected 
開發者ID:securityclippy,項目名稱:elasticintel,代碼行數:9,代碼來源:test_tools.py

示例12: get_value

# 需要導入模塊: from pandas.core.tools import datetimes [as 別名]
# 或者: from pandas.core.tools.datetimes import parse_time_string [as 別名]
def get_value(self, series, key):
        """
        Fast lookup of value from 1-dimensional ndarray. Only use this if you
        know what you're doing
        """
        s = com.values_from_object(series)
        try:
            return com.maybe_box(self,
                                 super(PeriodIndex, self).get_value(s, key),
                                 series, key)
        except (KeyError, IndexError):
            try:
                asdt, parsed, reso = parse_time_string(key, self.freq)
                grp = resolution.Resolution.get_freq_group(reso)
                freqn = resolution.get_freq_group(self.freq)

                vals = self._ndarray_values

                # if our data is higher resolution than requested key, slice
                if grp < freqn:
                    iv = Period(asdt, freq=(grp, 1))
                    ord1 = iv.asfreq(self.freq, how='S').ordinal
                    ord2 = iv.asfreq(self.freq, how='E').ordinal

                    if ord2 < vals[0] or ord1 > vals[-1]:
                        raise KeyError(key)

                    pos = np.searchsorted(self._ndarray_values, [ord1, ord2])
                    key = slice(pos[0], pos[1] + 1)
                    return series[key]
                elif grp == freqn:
                    key = Period(asdt, freq=self.freq).ordinal
                    return com.maybe_box(self, self._engine.get_value(s, key),
                                         series, key)
                else:
                    raise KeyError(key)
            except TypeError:
                pass

            period = Period(key, self.freq)
            key = period.value if isna(period) else period.ordinal
            return com.maybe_box(self, self._engine.get_value(s, key),
                                 series, key) 
開發者ID:Frank-qlu,項目名稱:recruit,代碼行數:45,代碼來源:period.py

示例13: get_value

# 需要導入模塊: from pandas.core.tools import datetimes [as 別名]
# 或者: from pandas.core.tools.datetimes import parse_time_string [as 別名]
def get_value(self, series, key):
        """
        Fast lookup of value from 1-dimensional ndarray. Only use this if you
        know what you're doing
        """
        s = com._values_from_object(series)
        try:
            return com._maybe_box(self,
                                  super(PeriodIndex, self).get_value(s, key),
                                  series, key)
        except (KeyError, IndexError):
            try:
                asdt, parsed, reso = parse_time_string(key, self.freq)
                grp = resolution.Resolution.get_freq_group(reso)
                freqn = resolution.get_freq_group(self.freq)

                vals = self._ndarray_values

                # if our data is higher resolution than requested key, slice
                if grp < freqn:
                    iv = Period(asdt, freq=(grp, 1))
                    ord1 = iv.asfreq(self.freq, how='S').ordinal
                    ord2 = iv.asfreq(self.freq, how='E').ordinal

                    if ord2 < vals[0] or ord1 > vals[-1]:
                        raise KeyError(key)

                    pos = np.searchsorted(self._ndarray_values, [ord1, ord2])
                    key = slice(pos[0], pos[1] + 1)
                    return series[key]
                elif grp == freqn:
                    key = Period(asdt, freq=self.freq).ordinal
                    return com._maybe_box(self, self._engine.get_value(s, key),
                                          series, key)
                else:
                    raise KeyError(key)
            except TypeError:
                pass

            key = Period(key, self.freq).ordinal
            return com._maybe_box(self, self._engine.get_value(s, key),
                                  series, key) 
開發者ID:birforce,項目名稱:vnpy_crypto,代碼行數:44,代碼來源:period.py

示例14: get_value

# 需要導入模塊: from pandas.core.tools import datetimes [as 別名]
# 或者: from pandas.core.tools.datetimes import parse_time_string [as 別名]
def get_value(self, series, key):
        """
        Fast lookup of value from 1-dimensional ndarray. Only use this if you
        know what you're doing
        """
        s = com._values_from_object(series)
        try:
            return com._maybe_box(self,
                                  super(PeriodIndex, self).get_value(s, key),
                                  series, key)
        except (KeyError, IndexError):
            try:
                asdt, parsed, reso = parse_time_string(key, self.freq)
                grp = frequencies.Resolution.get_freq_group(reso)
                freqn = frequencies.get_freq_group(self.freq)

                vals = self._values

                # if our data is higher resolution than requested key, slice
                if grp < freqn:
                    iv = Period(asdt, freq=(grp, 1))
                    ord1 = iv.asfreq(self.freq, how='S').ordinal
                    ord2 = iv.asfreq(self.freq, how='E').ordinal

                    if ord2 < vals[0] or ord1 > vals[-1]:
                        raise KeyError(key)

                    pos = np.searchsorted(self._values, [ord1, ord2])
                    key = slice(pos[0], pos[1] + 1)
                    return series[key]
                elif grp == freqn:
                    key = Period(asdt, freq=self.freq).ordinal
                    return com._maybe_box(self, self._engine.get_value(s, key),
                                          series, key)
                else:
                    raise KeyError(key)
            except TypeError:
                pass

            key = Period(key, self.freq).ordinal
            return com._maybe_box(self, self._engine.get_value(s, key),
                                  series, key) 
開發者ID:nccgroup,項目名稱:Splunking-Crime,代碼行數:44,代碼來源:period.py


注:本文中的pandas.core.tools.datetimes.parse_time_string方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。