本文整理汇总了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
示例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
示例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)
示例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
示例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'))
示例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)
示例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'))
示例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
示例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)
示例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)
示例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
示例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)
示例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)
示例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)