本文整理汇总了Python中datetime.datetime.date方法的典型用法代码示例。如果您正苦于以下问题:Python datetime.date方法的具体用法?Python datetime.date怎么用?Python datetime.date使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类datetime.datetime
的用法示例。
在下文中一共展示了datetime.date方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: datereader
# 需要导入模块: from datetime import datetime [as 别名]
# 或者: from datetime.datetime import date [as 别名]
def datereader(dateattribute, parsingfunction=ymdparser):
"""Return a function that converts a certain dict member to a datetime.date
When setting, fromfinder for a tables.SlowlyChangingDimension, this
method can be used for generating a function that picks the relevant
dictionary member from each row and converts it.
Arguments:
- dateattribute: the attribute the generated function should read
- parsingfunction: the parsing function that converts the string
to a datetime.date
"""
def readerfunction(targetconnection, row, namemapping={}):
atttouse = (namemapping.get(dateattribute) or dateattribute)
return parsingfunction(row[atttouse]) # a datetime.date
return readerfunction
示例2: _convert_1d
# 需要导入模块: from datetime import datetime [as 别名]
# 或者: from datetime.datetime import date [as 别名]
def _convert_1d(values, units, axis):
if not hasattr(axis, 'freq'):
raise TypeError('Axis must have `freq` set to convert to Periods')
valid_types = (compat.string_types, datetime,
Period, pydt.date, pydt.time, np.datetime64)
if (isinstance(values, valid_types) or is_integer(values) or
is_float(values)):
return get_datevalue(values, axis.freq)
elif isinstance(values, PeriodIndex):
return values.asfreq(axis.freq)._ndarray_values
elif isinstance(values, Index):
return values.map(lambda x: get_datevalue(x, axis.freq))
elif lib.infer_dtype(values, skipna=False) == 'period':
# https://github.com/pandas-dev/pandas/issues/24304
# convert ndarray[period] -> PeriodIndex
return PeriodIndex(values, freq=axis.freq)._ndarray_values
elif isinstance(values, (list, tuple, np.ndarray, Index)):
return [get_datevalue(x, axis.freq) for x in values]
return values
示例3: axisinfo
# 需要导入模块: from datetime import datetime [as 别名]
# 或者: from datetime.datetime import date [as 别名]
def axisinfo(unit, axis):
"""
Return the :class:`~matplotlib.units.AxisInfo` for *unit*.
*unit* is a tzinfo instance or None.
The *axis* argument is required but not used.
"""
tz = unit
majloc = PandasAutoDateLocator(tz=tz)
majfmt = PandasAutoDateFormatter(majloc, tz=tz)
datemin = pydt.date(2000, 1, 1)
datemax = pydt.date(2010, 1, 1)
return units.AxisInfo(majloc=majloc, majfmt=majfmt, label='',
default_limits=(datemin, datemax))
示例4: apply
# 需要导入模块: from datetime import datetime [as 别名]
# 或者: from datetime.datetime import date [as 别名]
def apply(self, other):
current_easter = easter(other.year)
current_easter = datetime(current_easter.year,
current_easter.month, current_easter.day)
current_easter = conversion.localize_pydatetime(current_easter,
other.tzinfo)
n = self.n
if n >= 0 and other < current_easter:
n -= 1
elif n < 0 and other > current_easter:
n += 1
# TODO: Why does this handle the 0 case the opposite of others?
# NOTE: easter returns a datetime.date so we have to convert to type of
# other
new = easter(other.year + n)
new = datetime(new.year, new.month, new.day, other.hour,
other.minute, other.second, other.microsecond)
return new
示例5: test_dt64ser_cmp_date_invalid
# 需要导入模块: from datetime import datetime [as 别名]
# 或者: from datetime.datetime import date [as 别名]
def test_dt64ser_cmp_date_invalid(self, box_with_array):
# GH#19800 datetime.date comparison raises to
# match DatetimeIndex/Timestamp. This also matches the behavior
# of stdlib datetime.datetime
ser = pd.date_range('20010101', periods=10)
date = ser.iloc[0].to_pydatetime().date()
ser = tm.box_expected(ser, box_with_array)
assert not (ser == date).any()
assert (ser != date).all()
with pytest.raises(TypeError):
ser > date
with pytest.raises(TypeError):
ser < date
with pytest.raises(TypeError):
ser >= date
with pytest.raises(TypeError):
ser <= date
示例6: dt64arr_cmp_non_datetime
# 需要导入模块: from datetime import datetime [as 别名]
# 或者: from datetime.datetime import date [as 别名]
def dt64arr_cmp_non_datetime(self, tz_naive_fixture, box_with_array):
# GH#19301 by convention datetime.date is not considered comparable
# to Timestamp or DatetimeIndex. This may change in the future.
tz = tz_naive_fixture
dti = pd.date_range('2016-01-01', periods=2, tz=tz)
dtarr = tm.box_expected(dti, box_with_array)
other = datetime(2016, 1, 1).date()
assert not (dtarr == other).any()
assert (dtarr != other).all()
with pytest.raises(TypeError):
dtarr < other
with pytest.raises(TypeError):
dtarr <= other
with pytest.raises(TypeError):
dtarr > other
with pytest.raises(TypeError):
dtarr >= other
示例7: __deserialize_date
# 需要导入模块: from datetime import datetime [as 别名]
# 或者: from datetime.datetime import date [as 别名]
def __deserialize_date(self, string):
"""
Deserializes string to date.
:param string: str.
:return: date.
"""
try:
from dateutil.parser import parse
return parse(string).date()
except ImportError:
return string
except ValueError:
raise ApiException(
status=0,
reason="Failed to parse `{0}` into a date object".format(string)
)
示例8: test_sort_rows_datetime
# 需要导入模块: from datetime import datetime [as 别名]
# 或者: from datetime.datetime import date [as 别名]
def test_sort_rows_datetime():
import datetime
from dataflows import sort_rows
f = Flow(
[
{'a': datetime.date(2000, 1, 3)},
{'a': datetime.date(2010, 1, 2)},
{'a': datetime.date(2020, 1, 1)},
],
sort_rows(key='{a}'),
)
results, _, _ = f.results()
assert list(results[0]) == [
{'a': datetime.date(2000, 1, 3)},
{'a': datetime.date(2010, 1, 2)},
{'a': datetime.date(2020, 1, 1)},
]
示例9: test_load_dates_timezones
# 需要导入模块: from datetime import datetime [as 别名]
# 或者: from datetime.datetime import date [as 别名]
def test_load_dates_timezones():
from dataflows import Flow, checkpoint
from datetime import datetime, timezone
import shutil
dates = [
datetime.now(),
datetime.now(timezone.utc).astimezone()
]
shutil.rmtree('.checkpoints/test_load_dates_timezones', ignore_errors=True)
Flow(
[{'date': d.date(), 'datetime': d} for d in dates],
checkpoint('test_load_dates_timezones')
).process()
results = Flow(
checkpoint('test_load_dates_timezones')
).results()
assert list(map(lambda x: x['date'], results[0][0])) == \
list(map(lambda x: x.date(), dates))
assert list(map(lambda x: x['datetime'], results[0][0])) == \
list(map(lambda x: x, dates))
示例10: _convert_1d
# 需要导入模块: from datetime import datetime [as 别名]
# 或者: from datetime.datetime import date [as 别名]
def _convert_1d(values, units, axis):
if not hasattr(axis, 'freq'):
raise TypeError('Axis must have `freq` set to convert to Periods')
valid_types = (compat.string_types, datetime,
Period, pydt.date, pydt.time, np.datetime64)
if (isinstance(values, valid_types) or is_integer(values) or
is_float(values)):
return get_datevalue(values, axis.freq)
if isinstance(values, PeriodIndex):
return values.asfreq(axis.freq)._ndarray_values
if isinstance(values, Index):
return values.map(lambda x: get_datevalue(x, axis.freq))
if is_period_arraylike(values):
return PeriodIndex(values, freq=axis.freq)._ndarray_values
if isinstance(values, (list, tuple, np.ndarray, Index)):
return [get_datevalue(x, axis.freq) for x in values]
return values
示例11: apply_index
# 需要导入模块: from datetime import datetime [as 别名]
# 或者: from datetime.datetime import date [as 别名]
def apply_index(self, i):
# determine how many days away from the 1st of the month we are
days_from_start = i.to_perioddelta('M').asi8
delta = Timedelta(days=self.day_of_month - 1).value
# get boolean array for each element before the day_of_month
before_day_of_month = days_from_start < delta
# get boolean array for each element after the day_of_month
after_day_of_month = days_from_start > delta
# determine the correct n for each date in i
roll = self._get_roll(i, before_day_of_month, after_day_of_month)
# isolate the time since it will be striped away one the next line
time = i.to_perioddelta('D')
# apply the correct number of months
i = (i.to_period('M') + (roll // 2)).to_timestamp()
# apply the correct day
i = self._apply_index_days(i, roll)
return i + time
示例12: __init__
# 需要导入模块: from datetime import datetime [as 别名]
# 或者: from datetime.datetime import date [as 别名]
def __init__(self, sep=None):
"""
:param sep:
A single character that separates date and time portions. If
``None``, the parser will accept any single character.
For strict ISO-8601 adherence, pass ``'T'``.
"""
if sep is not None:
if (len(sep) != 1 or ord(sep) >= 128 or sep in '0123456789'):
raise ValueError('Separator must be a single, non-numeric ' +
'ASCII character')
sep = sep.encode('ascii')
self._sep = sep
示例13: parse_isodate
# 需要导入模块: from datetime import datetime [as 别名]
# 或者: from datetime.datetime import date [as 别名]
def parse_isodate(self, datestr):
"""
Parse the date portion of an ISO string.
:param datestr:
The string portion of an ISO string, without a separator
:return:
Returns a :class:`datetime.date` object
"""
components, pos = self._parse_isodate(datestr)
if pos < len(datestr):
raise ValueError('String contains unknown ISO ' +
'components: {}'.format(datestr))
return date(*components)
示例14: _calculate_weekdate
# 需要导入模块: from datetime import datetime [as 别名]
# 或者: from datetime.datetime import date [as 别名]
def _calculate_weekdate(self, year, week, day):
"""
Calculate the day of corresponding to the ISO year-week-day calendar.
This function is effectively the inverse of
:func:`datetime.date.isocalendar`.
:param year:
The year in the ISO calendar
:param week:
The week in the ISO calendar - range is [1, 53]
:param day:
The day in the ISO calendar - range is [1 (MON), 7 (SUN)]
:return:
Returns a :class:`datetime.date`
"""
if not 0 < week < 54:
raise ValueError('Invalid week: {}'.format(week))
if not 0 < day < 8: # Range is 1-7
raise ValueError('Invalid weekday: {}'.format(day))
# Get week 1 for the specific year:
jan_4 = date(year, 1, 4) # Week 1 always has January 4th in it
week_1 = jan_4 - timedelta(days=jan_4.isocalendar()[2] - 1)
# Now add the specific number of weeks and days to get what we want
week_offset = (week - 1) * 7 + (day - 1)
return week_1 + timedelta(days=week_offset)
示例15: today
# 需要导入模块: from datetime import datetime [as 别名]
# 或者: from datetime.datetime import date [as 别名]
def today(ignoredtargetconn=None, ignoredrow=None, ignorednamemapping=None):
"""Return the date of the first call this method as a datetime.date object.
"""
global _today
if _today is not None:
return _today
_today = date.today()
return _today