Python calendar.monthrange() Examples

The following are 30 code examples of calendar.monthrange(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module calendar , or try the search function .
Example #1
Source File: common.py    From koku with GNU Affero General Public License v3.0 6 votes vote down vote up
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 
Example #2
Source File: calculo_ir.py    From ir with Mozilla Public License 2.0 6 votes vote down vote up
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) 
Example #3
Source File: gui_utilities.py    From king-phisher with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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) 
Example #4
Source File: _parser.py    From recruit with Apache License 2.0 6 votes vote down vote up
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 
Example #5
Source File: _parser.py    From vnpy_crypto with MIT License 6 votes vote down vote up
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 
Example #6
Source File: _parser.py    From plugin.video.emby with GNU General Public License v3.0 6 votes vote down vote up
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 
Example #7
Source File: date_util.py    From OpenData with Apache License 2.0 6 votes vote down vote up
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 
Example #8
Source File: views.py    From ACE with Apache License 2.0 6 votes vote down vote up
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 
Example #9
Source File: test_parameters.py    From pywr with GNU General Public License v3.0 6 votes vote down vote up
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() 
Example #10
Source File: test_parameters.py    From pywr with GNU General Public License v3.0 6 votes vote down vote up
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() 
Example #11
Source File: test_monthday_setbuilder.py    From aws-ops-automator with Apache License 2.0 6 votes vote down vote up
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}) 
Example #12
Source File: common.py    From koku with GNU Affero General Public License v3.0 6 votes vote down vote up
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)) 
Example #13
Source File: aws_report_summary_updater.py    From koku with GNU Affero General Public License v3.0 6 votes vote down vote up
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 
Example #14
Source File: ocp_report_summary_updater.py    From koku with GNU Affero General Public License v3.0 6 votes vote down vote up
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 
Example #15
Source File: monthday_setbuilder.py    From aws-ops-automator with Apache License 2.0 6 votes vote down vote up
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] 
Example #16
Source File: test_calendar.py    From oss-ftp with MIT License 5 votes vote down vote up
def test_january(self):
        # Tests valid lower boundary case.
        self.assertEqual(calendar.monthrange(2004,1), (3,31)) 
Example #17
Source File: test_calendar.py    From oss-ftp with MIT License 5 votes vote down vote up
def test_zeroth_month(self):
        # Tests low invalid boundary case.
        with self.assertRaises(calendar.IllegalMonthError):
            calendar.monthrange(2004, 0) 
Example #18
Source File: test_calendar.py    From oss-ftp with MIT License 5 votes vote down vote up
def test_february_nonleap(self):
        # Tests February in non-leap year.
        self.assertEqual(calendar.monthrange(2010,2), (0,28)) 
Example #19
Source File: test_calendar.py    From oss-ftp with MIT License 5 votes vote down vote up
def test_december(self):
        # Tests valid upper boundary case.
        self.assertEqual(calendar.monthrange(2004,12), (2,31)) 
Example #20
Source File: test_calendar.py    From oss-ftp with MIT License 5 votes vote down vote up
def test_february_leap(self):
        # Tests February during leap year.
        self.assertEqual(calendar.monthrange(2004,2), (6,29)) 
Example #21
Source File: __init__.py    From financial_life with Apache License 2.0 5 votes vote down vote up
def add_month(self, months):
        """ introduces calculation with months """
        new_year = self.year + int((self.month + months - 1)/12)
        new_month = ((self.month + months - 1) % 12) + 1
        new_day = min(self.day, monthrange(new_year, new_month)[1])
        return Bank_Date(year = new_year, month = new_month, day = new_day) 
Example #22
Source File: __init__.py    From financial_life with Apache License 2.0 5 votes vote down vote up
def is_end_of_month(self):
        """ returns true, if the current day is the end of month """
        return monthrange(self.year, self.month)[1] == self.day 
Example #23
Source File: test_calendar.py    From BinderFilter with MIT License 5 votes vote down vote up
def test_january(self):
        # Tests valid lower boundary case.
        self.assertEqual(calendar.monthrange(2004,1), (3,31)) 
Example #24
Source File: dateformat.py    From bioforum with MIT License 5 votes vote down vote up
def t(self):
        "Number of days in the given month; i.e. '28' to '31'"
        return '%02d' % calendar.monthrange(self.data.year, self.data.month)[1] 
Example #25
Source File: sportcrawler.py    From KoreaNewsCrawler with Apache License 2.0 5 votes vote down vote up
def Make_url(self, URL, startyear, lastyear, startmonth, lastmonth):
        Maked_url = []
        final_startmonth = startmonth
        final_lastmonth = lastmonth
        for year in range(startyear, lastyear + 1):
            if year != lastyear:
                startmonth = 1
                lastmonth = 12
            else:
                startmonth = final_startmonth
                lastmonth = final_lastmonth
            for Month in range(startmonth, lastmonth + 1):
                for Month_Day in range(1, calendar.monthrange(year, Month)[1] + 1):
                    url = URL
                    if len(str(Month)) == 1:
                        Month = "0" + str(Month)
                    if len(str(Month_Day)) == 1:
                        Month_Day = "0" + str(Month_Day)
                    url = url + str(year) + str(Month) + str(Month_Day)
                    final_url = url  # page 날짜 정보만 있고 page 정보가 없는 url 임시 저장
                    totalpage = self.javascript_totalpage(url)  # TotalPage 확인
                    for page in range(1, totalpage + 1):
                        url = final_url  # url page 초기화
                        url = url + "&page=" + str(page)
                        Maked_url.append(url)  # [[page1,page2,page3 ....]
        return Maked_url


# Main 
Example #26
Source File: articlecrawler.py    From KoreaNewsCrawler with Apache License 2.0 5 votes vote down vote up
def make_news_page_url(category_url, start_year, end_year, start_month, end_month):
        made_urls = []
        for year in range(start_year, end_year + 1):
            if start_year == end_year:
                year_startmonth = start_month
                year_endmonth = end_month
            else:
                if year == start_year:
                    year_startmonth = start_month
                    year_endmonth = 12
                elif year == end_year:
                    year_startmonth = 1
                    year_endmonth = end_month
                else:
                    year_startmonth = 1
                    year_endmonth = 12
            
            for month in range(year_startmonth, year_endmonth + 1):
                for month_day in range(1, calendar.monthrange(year, month)[1] + 1):
                    if len(str(month)) == 1:
                        month = "0" + str(month)
                    if len(str(month_day)) == 1:
                        month_day = "0" + str(month_day)
                        
                    # 날짜별로 Page Url 생성
                    url = category_url + str(year) + str(month) + str(month_day)

                    # totalpage는 네이버 페이지 구조를 이용해서 page=10000으로 지정해 totalpage를 알아냄
                    # page=10000을 입력할 경우 페이지가 존재하지 않기 때문에 page=totalpage로 이동 됨 (Redirect)
                    totalpage = ArticleParser.find_news_totalpage(url + "&page=10000")
                    for page in range(1, totalpage + 1):
                        made_urls.append(url + "&page=" + str(page))
        return made_urls 
Example #27
Source File: _parser.py    From vnpy_crypto with MIT License 5 votes vote down vote up
def could_be_day(self, value):
        if self.has_day:
            return False
        elif not self.has_month:
            return 1 <= value <= 31
        elif not self.has_year:
            # Be permissive, assume leapyear
            month = self[self.mstridx]
            return 1 <= value <= monthrange(2000, month)[1]
        else:
            month = self[self.mstridx]
            year = self[self.ystridx]
            return 1 <= value <= monthrange(year, month)[1] 
Example #28
Source File: test_offsets.py    From vnpy_crypto with MIT License 5 votes vote down vote up
def test_monthrange():
    import calendar
    for y in range(2000, 2013):
        for m in range(1, 13):
            assert tslib.monthrange(y, m) == calendar.monthrange(y, m)

####
# Misc function tests
#### 
Example #29
Source File: persons_service.py    From zou with GNU Affero General Public License v3.0 5 votes vote down vote up
def get_presence_logs(year, month):
    """
    Return arrays of presence for a given month, adapted for a CSV rendering.
    Rows are users and columns represent the days of given month.
    """
    persons = get_active_persons()
    headers = [str(year)]
    csv_content = []

    (_, limit) = monthrange(year, month)
    headers += [str(i) for i in range(1, limit + 1)]
    start_date = datetime.datetime(year, month, 1, 0, 0, 0)
    end_date = datetime.date.today() + relativedelta.relativedelta(months=1)

    csv_content.append(headers)
    for person in persons:
        row = [person["full_name"]]
        row += ["" for i in range(1, limit + 1)]
        logs = (
            DesktopLoginLog.query.filter(
                DesktopLoginLog.person_id == person["id"]
            )
            .filter(DesktopLoginLog.date >= start_date)
            .filter(DesktopLoginLog.date < end_date)
            .order_by(DesktopLoginLog.date)
            .all()
        )

        for log in logs:
            day = log.date.day
            row[day] = "X"
        csv_content.append(row)
    return csv_content 
Example #30
Source File: gregorian_calendar.py    From flask-calendar with The Unlicense 5 votes vote down vote up
def next_month_and_year(year: int, month: int) -> Tuple[int, int]:
        last_day_of_month = calendar.monthrange(year, month)[1]
        next_month_date = date(year, month, last_day_of_month) + timedelta(days=2)
        return next_month_date.month, next_month_date.year