本文整理匯總了Python中calendar.monthrange方法的典型用法代碼示例。如果您正苦於以下問題:Python calendar.monthrange方法的具體用法?Python calendar.monthrange怎麽用?Python calendar.monthrange使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類calendar
的用法示例。
在下文中一共展示了calendar.monthrange方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: gtk_calendar_get_pydate
# 需要導入模塊: import calendar [as 別名]
# 或者: from calendar import monthrange [as 別名]
def gtk_calendar_get_pydate(gtk_calendar):
"""
Get the Python date from a :py:class:`Gtk.Calendar` instance. If the day
in *gtk_calendar* is not within the valid range for the specified month, it
will be rounded to the closest value (i.e. 0 for unset will become 1 etc.).
:param gtk_calendar: The calendar to get the date from.
:type gtk_calendar: :py:class:`Gtk.Calendar`
:return: The date as returned by the calendar's :py:meth:`~Gtk.Calendar.get_date` method.
:rtype: :py:class:`datetime.date`
"""
if not isinstance(gtk_calendar, Gtk.Calendar):
raise ValueError('calendar must be a Gtk.Calendar instance')
year, month, day = gtk_calendar.get_date()
month += 1 # account for Gtk.Calendar starting at 0
_, last_day_of_month = calendar.monthrange(year, month)
day = max(1, min(day, last_day_of_month))
return datetime.date(year, month, day)
示例2: __init__
# 需要導入模塊: import calendar [as 別名]
# 或者: from calendar import monthrange [as 別名]
def __init__(self, year, month):
"""
Initializes monthday set builder.
:param year: Year of month to build sets for, only required for month aware 'W' and 'L' features in expressions
:param month: Month to build sets for, only required for month aware 'W' and 'L' features in expressions
"""
self.year = year
self.month = month
self._firstweekday, self._lastday = calendar.monthrange(year, month)
SetBuilder.__init__(self,
min_value=1,
max_value=self._lastday,
offset=1,
ignore_case=False,
wrap=False,
last_item_wildcard=MonthdaySetBuilder.WILDCARD_LAST_WEEKDAY)
self._post_custom_parsers = [self._parse_weekday]
示例3: test_W_wildcard
# 需要導入模塊: import calendar [as 別名]
# 或者: from calendar import monthrange [as 別名]
def test_W_wildcard(self):
years = [2016, 2017] # leap and normal year
for year in years:
for month in range(1, 13):
_, days = calendar.monthrange(year, month)
for day in range(1, days):
weekday = calendar.weekday(year, month, day)
result = day
if weekday == 5:
result = day - 1 if day > 1 else day + 2
elif weekday == 6:
result = day + 1 if day < days else day - 2
self.assertEqual(MonthdaySetBuilder(year, month).build(str(day) + "W"), {result})
示例4: test_interpolation_month_start
# 需要導入模塊: import calendar [as 別名]
# 或者: from calendar import monthrange [as 別名]
def test_interpolation_month_start(self, simple_linear_model):
"""Test interpolating monthly values from first day of the month."""
model = simple_linear_model
values = np.arange(12, dtype=np.float64)
p = MonthlyProfileParameter(model, values, interp_day='first')
model.setup()
@assert_rec(model, p)
def expected_func(timestep, scenario_index):
imth = timestep.month - 1
days_in_month = calendar.monthrange(timestep.year, timestep.month)[1]
day = timestep.day
# Perform linear interpolation
x = (day - 1) / (days_in_month - 1)
return values[imth] * (1 - x) + values[(imth+1) % 12] * x
model.run()
示例5: test_interpolation_month_end
# 需要導入模塊: import calendar [as 別名]
# 或者: from calendar import monthrange [as 別名]
def test_interpolation_month_end(self, simple_linear_model):
"""Test interpolating monthly values from last day of the month."""
model = simple_linear_model
values = np.arange(12, dtype=np.float64)
p = MonthlyProfileParameter(model, values, interp_day='last')
model.setup()
@assert_rec(model, p)
def expected_func(timestep, scenario_index):
imth = timestep.month - 1
days_in_month = calendar.monthrange(timestep.year, timestep.month)[1]
day = timestep.day
# Perform linear interpolation
x = day / days_in_month
return values[(imth - 1) % 12] * (1 - x) + values[imth] * x
model.run()
示例6: _build_naive
# 需要導入模塊: import calendar [as 別名]
# 或者: from calendar import monthrange [as 別名]
def _build_naive(self, res, default):
repl = {}
for attr in ("year", "month", "day", "hour",
"minute", "second", "microsecond"):
value = getattr(res, attr)
if value is not None:
repl[attr] = value
if 'day' not in repl:
# If the default day exceeds the last day of the month, fall back
# to the end of the month.
cyear = default.year if res.year is None else res.year
cmonth = default.month if res.month is None else res.month
cday = default.day if res.day is None else res.day
if cday > monthrange(cyear, cmonth)[1]:
repl['day'] = monthrange(cyear, cmonth)[1]
naive = default.replace(**repl)
if res.weekday is not None and not res.day:
naive = naive + relativedelta.relativedelta(weekday=res.weekday)
return naive
示例7: calcula
# 需要導入模塊: import calendar [as 別名]
# 或者: from calendar import monthrange [as 別名]
def calcula(self):
hoje = datetime.datetime.now().date()
data_inicial = self.df['data'].min() + relativedelta(months=-1)
data = data_inicial = datetime.date(data_inicial.year, data_inicial.month, 1)
data_final = hoje + relativedelta(months=-1)
data_final = datetime.date(data_final.year, data_final.month, calendar.monthrange(data_final.year,data_final.month)[1])
self.mes_do_relatorio = self.__get_date_key__(data_final)
while data <= data_final:
self.datas.append(data)
data = data + relativedelta(months=1)
self.prejuizo_acumulado = {}
for tipo in TipoTicker:
self.__seta_prejuizo_acumulado(data_inicial, tipo, 0.0)
for index, data in enumerate(self.datas):
self.__seta_vendas_no_mes(data, vendas_no_mes(self.df, data.year, data.month))
for tipo in TipoTicker:
prejuizo_acumulado = self.calcula_prejuizo_acumulado(data, tipo)
self.__seta_prejuizo_acumulado(data, tipo, prejuizo_acumulado)
示例8: get_month_firstday_and_lastday
# 需要導入模塊: import calendar [as 別名]
# 或者: from calendar import monthrange [as 別名]
def get_month_firstday_and_lastday(year=None, month=None):
"""
:param year: 年份,默認是本年,可傳int或str類型
:param month: 月份,默認是本月,可傳int或str類型
:return: firstDay: 當月的第一天,datetime.date類型
lastDay: 當月的最後一天,datetime.date類型
"""
if year:
year = int(year)
else:
year = datetime.date.today().year
if month:
month = int(month)
else:
month = datetime.date.today().month
# 獲取當月第一天的星期和當月的總天數
firstDayWeekDay, monthRange = calendar.monthrange(year, month)
# 獲取當月的第一天
firstDay = datetime.date(year=year, month=month, day=1)
lastDay = datetime.date(year=year, month=month, day=monthRange)
return firstDay, lastDay
示例9: get_month_day_range
# 需要導入模塊: import calendar [as 別名]
# 或者: from calendar import monthrange [as 別名]
def get_month_day_range(date):
"""
For a date 'date' returns the start and end dateitime for the month of 'date'.
Month with 31 days:
>>> date = datetime(2011, 7, 31, 5, 27, 18)
>>> get_month_day_range(date)
(datetime.datetime(2011, 7, 1, 0, 0), datetime.datetime(2011, 7, 31, 23, 59, 59))
Month with 28 days:
>>> datetime(2011, 2, 15, 17, 8, 45)
>>> get_month_day_range(date)
(datetime.datetime(2011, 2, 1, 0, 0), datetime.datetime(2011, 2, 28, 23, 59, 59))
"""
start_time = date.replace(day=1, hour=0, minute=0, second=0)
last_day = calendar.monthrange(date.year, date.month)[1]
end_time = date.replace(day=last_day, hour=23, minute=59, second=59)
return start_time, end_time
示例10: _get_sql_inputs
# 需要導入模塊: import calendar [as 別名]
# 或者: from calendar import monthrange [as 別名]
def _get_sql_inputs(self, start_date, end_date):
"""Get the required inputs for running summary SQL."""
with AWSReportDBAccessor(self._schema) as accessor:
# This is the normal processing route
if self._manifest:
# Override the bill date to correspond with the manifest
bill_date = self._manifest.billing_period_start_datetime.date()
bills = accessor.get_cost_entry_bills_query_by_provider(self._provider.uuid)
bills = bills.filter(billing_period_start=bill_date).all()
first_bill = bills.filter(billing_period_start=bill_date).first()
do_month_update = False
with schema_context(self._schema):
if first_bill:
do_month_update = self._determine_if_full_summary_update_needed(first_bill)
if do_month_update:
last_day_of_month = calendar.monthrange(bill_date.year, bill_date.month)[1]
start_date = bill_date.strftime("%Y-%m-%d")
end_date = bill_date.replace(day=last_day_of_month)
end_date = end_date.strftime("%Y-%m-%d")
LOG.info("Overriding start and end date to process full month.")
return start_date, end_date
示例11: _get_sql_inputs
# 需要導入模塊: import calendar [as 別名]
# 或者: from calendar import monthrange [as 別名]
def _get_sql_inputs(self, start_date, end_date):
"""Get the required inputs for running summary SQL."""
# Default to this month's bill
with OCPReportDBAccessor(self._schema) as accessor:
if self._manifest:
# Override the bill date to correspond with the manifest
bill_date = self._manifest.billing_period_start_datetime.date()
report_periods = accessor.get_usage_period_query_by_provider(self._provider.uuid)
report_periods = report_periods.filter(report_period_start=bill_date).all()
do_month_update = True
with schema_context(self._schema):
if report_periods is not None and len(report_periods) > 0:
do_month_update = self._determine_if_full_summary_update_needed(report_periods[0])
if do_month_update:
last_day_of_month = calendar.monthrange(bill_date.year, bill_date.month)[1]
start_date = bill_date.strftime("%Y-%m-%d")
end_date = bill_date.replace(day=last_day_of_month)
end_date = end_date.strftime("%Y-%m-%d")
LOG.info("Overriding start and end date to process full month.")
LOG.info("Returning start: %s, end: %s", str(start_date), str(end_date))
return start_date, end_date
示例12: month_date_range_tuple
# 需要導入模塊: import calendar [as 別名]
# 或者: from calendar import monthrange [as 別名]
def month_date_range_tuple(for_date_time):
"""
Get a date range tuple for the given date.
Date range is aligned on the first day of the current
month and ends on the first day of the next month from the
specified date.
Args:
for_date_time (DateTime): The starting datetime object
Returns:
(DateTime, DateTime): Tuple of first day of month,
and first day of next month.
"""
start_month = for_date_time.replace(day=1, hour=0, minute=0, second=0, microsecond=0)
_, num_days = calendar.monthrange(for_date_time.year, for_date_time.month)
first_next_month = start_month + timedelta(days=num_days)
return start_month, first_next_month
示例13: month_date_range
# 需要導入模塊: import calendar [as 別名]
# 或者: from calendar import monthrange [as 別名]
def month_date_range(for_date_time):
"""
Get a formatted date range string for the given date.
Date range is aligned on the first day of the current
month and ends on the first day of the next month from the
specified date.
Args:
for_date_time (DateTime): The starting datetime object
Returns:
(String): "YYYYMMDD-YYYYMMDD", example: "19701101-19701201"
"""
start_month = for_date_time.replace(day=1, second=1, microsecond=1)
_, num_days = calendar.monthrange(for_date_time.year, for_date_time.month)
end_month = start_month.replace(day=num_days)
timeformat = "%Y%m%d"
return "{}-{}".format(start_month.strftime(timeformat), end_month.strftime(timeformat))
示例14: daysInMonth
# 需要導入模塊: import calendar [as 別名]
# 或者: from calendar import monthrange [as 別名]
def daysInMonth(cls, year, month):
return calendar.monthrange(year, month)
#
# Get date time from Epoch time.
#
# @param unixTime
# Unix time.
# Date and time.
#
示例15: _requires_date_attributes
# 需要導入模塊: import calendar [as 別名]
# 或者: from calendar import monthrange [as 別名]
def _requires_date_attributes(fn):
# this modifier is used to mark to use methods that need year, day and month which are optional for the builder
def check(self, *args, **kwargs):
if self._year is None or self._month is None or self._day is None:
raise ValueError(
"year, month and day parameters must be specified when creating the {} for using method {}".format(
self.__class__.__name__, fn.__name__))
# and if we're checking for the first time then get the first weekday and numbers for the month
if self._first_weekday_in_month is None:
self._first_weekday_in_month, self._days_in_month = calendar.monthrange(self._year, self._month)
# noinspection PyCallingNonCallable
return fn(self, *args, **kwargs)
check.__name__ = fn.__name__
return check
# noinspection PyArgumentList,PyArgumentList