Python calendar 模块,monthrange() 实例源码

我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用calendar.monthrange()

项目:zing    作者:evernote    | 项目源码 | 文件源码
def get_max_month_datetime(dt):
    """Returns the datetime representing the last microsecond of the month with
    respect to the `dt` aware datetime.
    """
    days_in_month = calendar.monthrange(dt.year, dt.month)[1]

    tz = timezone.get_default_timezone()
    new_dt = tz.normalize(
        dt.replace(day=days_in_month),
    )

    # DST adjustments could have shifted the month or day
    if new_dt.month != dt.month:
        new_dt = new_dt.replace(month=dt.month)
    if new_dt.day != days_in_month:
        new_dt = new_dt.replace(day=days_in_month)

    return new_dt.replace(hour=23, minute=59, second=59, microsecond=999999)
项目:fiscalyear    作者:adamjstewart    | 项目源码 | 文件源码
def _check_day(month, day):
    """Check if day is a valid day of month.

    :param month: The month to test
    :param day: The day to test
    :return: The day
    :rtype: int
    :raises TypeError: If month or day is not an int or int-like string
    :raises ValueError: If month or day is out of range
    """
    month = _check_month(month)
    day = _check_int(day)

    # Find the last day of the month
    # Use a non-leap year
    max_day = calendar.monthrange(2001, month)[1]

    if 1 <= day <= max_day:
        return day
    else:
        raise ValueError('day must be in %d..%d' % (1, max_day), day)
项目:account_arba    作者:tryton-ar    | 项目源码 | 文件源码
def import_census(cls, configs):
        """
        Import arba census.
        """
        partys = Pool().get('party.party').search([
                ('vat_number', '!=', None),
                ])

        ws = cls.conect_arba()
        Date = Pool().get('ir.date')
        _, end_date = monthrange(Date.today().year, Date.today().month)
        fecha_desde = Date.today().strftime('%Y%m') + '01'
        fecha_hasta = Date.today().strftime('%Y%m') + str(end_date)
        for party in partys:
            data = cls.get_arba_data(ws, party, fecha_desde, fecha_hasta)
            if data is not None:
                if data.AlicuotaPercepcion != '':
                    party.AlicuotaPercepcion = Decimal(data.AlicuotaPercepcion.replace(',','.'))
                if data.AlicuotaRetencion != '':
                    party.arba_retencion =  Decimal(data.AlicuotaRetencion.replace(',','.'))
                    party.arba_perception = Decimal(data.AlicuotaPercepcion.replace(',','.'))
                party.save()
                Transaction().cursor.commit()
项目:egt    作者:spanezz    | 项目源码 | 文件源码
def main(self):
        # TODO: move to Project and unit test it
        cutoff = datetime.datetime.strptime(self.args.month, "%Y-%m").date()
        cutoff = cutoff.replace(day=calendar.monthrange(cutoff.year, cutoff.month)[1])
        e = self.make_egt(self.args.projects)
        archive_results = {}
        for p in e.projects:
            # TODO: copy timebase and entry, ignore commands
            # TODO: generate initial timebase in archived log
            entries = list(l for l in p.log.entries if l.begin.date() <= cutoff)
            if not entries: continue
            archive_results[p.name] = self.write_archive(p, entries, cutoff)
            duration = sum(e.duration for e in entries)
            # TODO: use Meta.print
            if "name" not in p.meta._raw:
                print("Name:", p.name)
            p.meta.print()
            print("{}: {}".format("Total", format_duration(duration)))
            print()
            # TODO: use Log.print or entry.print
            for l in entries:
                l.print()
            print()
        for name, res in sorted(archive_results.items()):
            print("Archived {}: {}".format(name, res))
项目:yoda    作者:yoda-pa    | 项目源码 | 文件源码
def current_month_task_analysis():
    """
    current month task analysis
    """
    now = datetime.datetime.now()
    no_of_days_current_month = calendar.monthrange(now.year, now.month)[1]
    total_tasks = 0
    total_incomplete_tasks = 0
    list_of_files = list_of_tasks_files()
    for some_file in range(0, len(list_of_files)):
        list_of_files[some_file] = os.path.join(DIARY_CONFIG_FOLDER_PATH, list_of_files[some_file])
    for some_file in list_of_files:
        with open(some_file) as fp:
            contents = yaml.load(fp)
            for entry in contents['entries']:
                total_tasks += 1
                total_incomplete_tasks += (1 if entry['status'] == 0 else 0)
    percent_incomplete_task = total_incomplete_tasks * 100 / total_tasks
    percent_complete_task = 100 - percent_incomplete_task
    entry_frequency = total_tasks * 100 / no_of_days_current_month
    chalk.red('Percentage of incomplete task : ' + str(percent_incomplete_task))
    chalk.green('Percentage of complete task : ' + str(percent_complete_task))
    chalk.blue("Frequency of adding task (Task/Day) : " + str(entry_frequency))
项目:aws-ops-automator    作者:awslabs    | 项目源码 | 文件源码
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.assertEquals(MonthdaySetBuilder(year, month).build(str(day) + "W"), {result})
项目:aws-ops-automator    作者:awslabs    | 项目源码 | 文件源码
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,
                            ignorecase=False,
                            wrap=False,
                            last_item_wildcard=MonthdaySetBuilder.WILDCARD_LAST_WEEKDAY)

        self._post_custom_parsers = [self._parse_weekday]
项目:mimesis    作者:lk-geimfari    | 项目源码 | 文件源码
def date(self, start: int = 2000, end: int = 2035,
             fmt: str = '') -> str:
        """Generate a string representing of random date formatted for
        the locale or as specified.

        :param int start: Minimum value of year.
        :param int end: Maximum value of year.
        :param str fmt: Format string for date.
        :return: Formatted date.

        :Example:
            08/16/88 (en)
        """
        if not fmt:
            fmt = self._data['formats'].get('date')

        year = self.random.randint(start, end)
        month = self.random.randint(1, 12)
        d = date(year, month, self.random.randint(
            1, monthrange(year, month)[1]))
        return d.strftime(fmt)
项目:gooderp_org    作者:osbzr    | 项目源码 | 文件源码
def _get_next_report_date(self, cr, uid, ids, field_name, arg, context=None):
        """Return the next report date based on the last report date and report
        period.

        :return: a string in DEFAULT_SERVER_DATE_FORMAT representing the date"""
        res = {}
        for challenge in self.browse(cr, uid, ids, context=context):
            last = datetime.strptime(challenge.last_report_date, DF).date()
            if challenge.report_message_frequency == 'daily':
                next = last + timedelta(days=1)
                res[challenge.id] = next.strftime(DF)
            elif challenge.report_message_frequency == 'weekly':
                next = last + timedelta(days=7)
                res[challenge.id] = next.strftime(DF)
            elif challenge.report_message_frequency == 'monthly':
                month_range = calendar.monthrange(last.year, last.month)
                next = last.replace(day=month_range[1]) + timedelta(days=1)
                res[challenge.id] = next.strftime(DF)
            elif challenge.report_message_frequency == 'yearly':
                res[challenge.id] = last.replace(year=last.year + 1).strftime(DF)
            # frequency == 'once', reported when closed only
            else:
                res[challenge.id] = False

        return res
项目:beansoup    作者:fxtlabs    | 项目源码 | 文件源码
def lowest_end(date, first_day=1):
    """Compute the ending date of the monthly period containing the given date.

    More formally, given a monthly cycle starting on `first_day` day of the month,
    it computes the lowest ending date that is greater than or equal to the given
    `date`.  Note that the ending date is inclusive, i.e. it is included in the
    monthly period.

    Args:
      date (datetime.date): An arbitrary date.
      first_day (int): The first day of the monthly cycle. It must fall
        in the interval [1,28].

    Returns:
      datetime.date: The ending date of the monthly period containing the given date.
    """
    start = greatest_start(date, first_day=first_day)
    _, length = calendar.monthrange(start.year, start.month)
    return start + datetime.timedelta(days=length-1)
项目:beansoup    作者:fxtlabs    | 项目源码 | 文件源码
def next(date):
    """Add one month to the given date.

    Args:
      date (datetime.date): The starting date.

    Returns:
      datetime.date:  One month after the starting date unless the starting
      date falls on a day that is not in the next month; in that case, it
      returns the last day of the next month.

    Example:

      >>> import datetime
      >>> next(datetime.date(2016, 1, 31))
      datetime.date(2016, 2, 29)

    """
    year, month = (date.year, date.month + 1) if date.month < 12 else (date.year + 1, 1)
    _, length = calendar.monthrange(year, month)
    day = min(length, date.day)
    return datetime.date(year, month, day)
项目:beansoup    作者:fxtlabs    | 项目源码 | 文件源码
def prev(date):
    """Subtract one month from the given date.

    Args:
      date (datetime.date): The starting date.

    Returns:
      datetime.date:  One month before the starting date unless the starting
      date falls on a day that is not in the previous month; in that case, it
      returns the last day of the previous month.

    Example:

      >>> import datetime
      >>> prev(datetime.date(2016, 3, 31))
      datetime.date(2016, 2, 29)

    """
    year, month = (date.year, date.month - 1) if date.month > 1 else (date.year - 1, 12)
    _, length = calendar.monthrange(year, month)
    day = min(length, date.day)
    return datetime.date(year, month, day)
项目:pyriodic    作者:Ayehavgunne    | 项目源码 | 文件源码
def increment(self, when):
        """
        Takes a datetime object and if it is in the past compared to the present it will
        add the defined interval of time to it till it is in the future
        """
        while not self.is_in_future(when):
            n = now()
            if self.interval == 'daily':
                when = when + timedelta(days=1)
            elif self.interval == 'weekly':
                when = when + timedelta(days=7)
            elif self.interval == 'monthly':
                when = when + timedelta(days=monthrange(n.year, n.month)[1])
            elif self.interval == 'yearly':
                if isleap(n.year) and self.is_in_future(datetime(year=n.year, month=2, day=29)):
                    when = when + timedelta(days=366)
                else:
                    when = when + timedelta(days=365)
        return when
项目:hdhp.py    作者:Networks-Learning    | 项目源码 | 文件源码
def month_add(t1, months):
    """Adds a number of months to the given date.


    Note
    ----
    The decimal part of the value corresponds to the fraction of days of the
    last month that will be added.


    Parameters
    ----------
    t1 : datetime object

    months : float


    Returns
    -------
    t2 : datetime object
    """
    t2 = t1 + relativedelta(months=int(months // 1))
    days_in_month = calendar.monthrange(t2.year, t2.month)[1]
    t2 = t2 + datetime.timedelta(seconds=days_in_month * 86400 * (months % 1))
    return t2
项目:MOSPAT    作者:CR2MOS    | 项目源码 | 文件源码
def timevect(d_StartDate, d_EndDate, c_TimeFreq, DT=None):
    f_Time = []
    d_Time = []
    while d_StartDate <= d_EndDate:
        d_Time.append(d_StartDate)
        f_Time.append(date2num(d_StartDate))
        f_Date_aux = date2num(d_StartDate)
        if c_TimeFreq == 'Monthly':
            DT_aux = monthrange(num2date(f_Date_aux).year, num2date(f_Date_aux).month)[1]
            DT = dt.timedelta(days=DT_aux)
        elif c_TimeFreq == 'Yearly':
            # finding out if it is a leap-year
            if isleap(d_StartDate.year + 1):
                DT = dt.timedelta(days=366)
            else:
                DT = dt.timedelta(days=365)
        d_StartDate += DT

    return f_Time, d_Time
项目:neteasenews    作者:tricomm    | 项目源码 | 文件源码
def main(startyear=2014, startmonth=1, startday=1, startnewsType=0):
    for year in range(2014, datetime.datetime.now().year + 1):
        if year < startyear:
            continue
        for month in range(1, 13):
            if month < startmonth:
                continue
            for day in range(1, calendar.monthrange(year, month)[1] + 1):
                if day < startday:
                    continue
                pool = multiprocessing.Pool()
                for newsType in range(0, 7):
                    if newsType < startnewsType:
                        continue
                    pool.apply_async(childProcess, args=(year, month, day, newsType))
                pool.close()
                pool.join()
                gc.collect()

## TODO:??????????????
# def restoreProcess():


## TODO:?????????
# def recoveryFromCrash():
项目:alexa-apple-calendar    作者:zanderxyz    | 项目源码 | 文件源码
def refresh_client(self, from_dt=None, to_dt=None):
        """
        Refreshes the CalendarService endpoint, ensuring that the
        event data is up-to-date. If no 'from_dt' or 'to_dt' datetimes
        have been given, the range becomes this month.
        """
        today = datetime.today()
        first_day, last_day = monthrange(today.year, today.month)
        if not from_dt:
            from_dt = datetime(today.year, today.month, first_day)
        if not to_dt:
            to_dt = datetime(today.year, today.month, last_day)
        params = dict(self.params)
        params.update({
            'lang': 'en-us',
            'usertz': get_localzone().zone,
            'startDate': from_dt.strftime('%Y-%m-%d'),
            'endDate': to_dt.strftime('%Y-%m-%d')
        })
        req = self.session.get(self._calendar_refresh_url, params=params)
        self.response = req.json()
项目:ccb_backup    作者:Andy-Fraley    | 项目源码 | 文件源码
def now_minus_delta_time(delta_time_string):
    curr_datetime = datetime.datetime.now(pytz.UTC)
    slop = 15 * 60 # 15 minutes of "slop" allowed in determining new backup is needed
    # curr_datetime = datetime.datetime(2016, 1, 7, 10, 52, 23, tzinfo=pytz.UTC)
    match = re.match('([1-9][0-9]*)([smhdwMY])', delta_time_string)
    if match is None:
        return None
    num_units = int(match.group(1))
    unit_char = match.group(2)
    seconds_per_unit = {'s': 1, 'm': 60, 'h': 3600, 'd': 86400, 'w': 604800}
    if unit_char in seconds_per_unit:
        delta_secs = (int(seconds_per_unit[unit_char]) * num_units) - slop
        return curr_datetime - datetime.timedelta(seconds=delta_secs)
    elif unit_char == 'M':
        month = curr_datetime.month - 1 - num_units
        year = int(curr_datetime.year + month / 12)
        month = month % 12 + 1
        day = min(curr_datetime.day, calendar.monthrange(year, month)[1])
        return datetime.datetime(year, month, day, curr_datetime.hour, curr_datetime.minute, curr_datetime.second,
            tzinfo=pytz.UTC) - datetime.timedelta(seconds=slop)
    else: # unit_char == 'Y'
        return datetime.datetime(curr_datetime.year + num_units, curr_datetime.month, curr_datetime.day,
            curr_datetime.hour, curr_datetime.minute, curr_datetime.second, tzinfo=pytz.UTC) - \
            datetime.timedelta(seconds=slop)
项目:web    作者:pyjobs    | 项目源码 | 文件源码
def get_month_period(period_range):
        """
        return a start date and a end date of x complete previous month
        :param period_range: number of months
        :return: date_from (datetime), date_to (datetime)
        """

        today = datetime.datetime.today().replace(hour=23, minute=59, second=59, microsecond=999999)
        current_month = today.replace(day=1)
        last_day_of_current_month = calendar.monthrange(today.year, today.month)[1]

        if today.day == last_day_of_current_month:
            date_from = current_month + relativedelta(months=-period_range - 1)
            date_to = today
        else:
            date_from = current_month + relativedelta(months=-period_range)
            date_to = current_month - datetime.timedelta(days=1)

        return date_from, date_to
项目:bday-app    作者:pybites    | 项目源码 | 文件源码
def bdays_month(month):
    if month not in range(1, 13):
        abort(400, 'Not a valid month')

    # SO questions/36155332
    _, num_days = calendar.monthrange(THIS_YEAR, month)
    start = date(THIS_YEAR, month, 1)
    end = date(THIS_YEAR, month, num_days)
    now = _get_current_date()

    # TODO: some duplication here with index()
    bdays = (Birthday.query.filter(Birthday.bday <= end)
             .filter(Birthday.bday >= start))

    month_name = calendar.month_name[month][:3]

    return render_template("index.html",
                           data=bdays,
                           now=now,
                           active_tab=month_name,
                           tabs=TABS)
项目:metronus    作者:Metronus    | 项目源码 | 文件源码
def __init__(self, task, month, year, employee):
        total_duration = 0
        self.id = task.id
        self.name = task.name
        self.durations = [(0, 0) for _ in range(0, calendar.monthrange(year, month)[1])]
        time_logs = TimeLog.objects.filter(workDate__year__gte=year,
                                           workDate__month__gte=month,
                                           workDate__year__lte=year,
                                           workDate__month__lte=month,
                                           task_id=task.id,
                                           employee_id=employee)

        for tl in time_logs:
            index = int(tl.workDate.day)-1
            self.durations[index] = (tl.duration, tl.id)
            total_duration += tl.duration
        self.durations.append((total_duration, 0))
项目:fintech_spider    作者:hee0624    | 项目源码 | 文件源码
def get_date(self, year):
        """        
        :param year: type(year): int 
        :return: str
        """
        # year_list = [year for year in range(1996, 2018)]
        # print(year_list)
        for month in range(1, 13):  # Jan - Dec
            date_list = list(range(calendar.monthrange(year, month)[1] + 1)[1:])
            if month in self.DIGIT_DICT:
                month = self.DIGIT_DICT[month]
            for date in date_list:
                if date in self.DIGIT_DICT:
                    date = self.DIGIT_DICT[date]
                yield "{0}-{1}-{2}".format(year, month, date)
                # yield "1996-01-10"    # 1
                # yield "1996-02-07"    # 1
                # yield "2016-02-07"    # 4
项目:fintech_spider    作者:hee0624    | 项目源码 | 文件源码
def get_date(self, year):
        """        
        :param year: type(year): int 
        :return: str
        """
        # year_list = [year for year in range(1996, 2018)]
        # print(year_list)
        for month in range(1, 13):  # Jan - Dec
            date_list = list(range(calendar.monthrange(year, month)[1] + 1)[1:])
            if month in self.DIGIT_DICT:
                month = self.DIGIT_DICT[month]
            for date in date_list:
                if date in self.DIGIT_DICT:
                    date = self.DIGIT_DICT[date]
                yield "{0}-{1}-{2}".format(year, month, date)
                # yield "1996-01-10"    # 1
                # yield "1996-02-07"    # 1
                # yield "2016-02-07"    # 4
项目:metrics    作者:Jeremy-Friedman    | 项目源码 | 文件源码
def get_next_value(self, date, field):
        # Figure out the weekday of the month's first day and the number of days in that month
        first_day_wday, last_day = monthrange(date.year, date.month)

        # Calculate which day of the month is the first of the target weekdays
        first_hit_day = self.weekday - first_day_wday + 1
        if first_hit_day <= 0:
            first_hit_day += 7

        # Calculate what day of the month the target weekday would be
        if self.option_num < 5:
            target_day = first_hit_day + self.option_num * 7
        else:
            target_day = first_hit_day + ((last_day - first_hit_day) / 7) * 7

        if target_day <= last_day and target_day >= date.day:
            return target_day
项目:metrics    作者:Jeremy-Friedman    | 项目源码 | 文件源码
def get_next_value(self, date, field):
        # Figure out the weekday of the month's first day and the number of days in that month
        first_day_wday, last_day = monthrange(date.year, date.month)

        # Calculate which day of the month is the first of the target weekdays
        first_hit_day = self.weekday - first_day_wday + 1
        if first_hit_day <= 0:
            first_hit_day += 7

        # Calculate what day of the month the target weekday would be
        if self.option_num < 5:
            target_day = first_hit_day + self.option_num * 7
        else:
            target_day = first_hit_day + ((last_day - first_hit_day) / 7) * 7

        if target_day <= last_day and target_day >= date.day:
            return target_day
项目:mltshp    作者:MLTSHP    | 项目源码 | 文件源码
def test_total_file_count_for_this_month(self):
        """
        tests that the current amount of new files uploaded for the current month is correct
        """
        images = ['red.gif', 'blue.gif', 'green.gif', 'love.gif']
        for image in images:
            file_name = image
            file_content_type = 'image/gif'
            file_path = os.path.abspath("test/files/%s" % (file_name))
            file_sha1 = Sourcefile.get_sha1_file_key(file_path)

            sf = Sharedfile.create_from_file(
                file_path = file_path,
                file_name = file_name,
                sha1_value = file_sha1,
                content_type = file_content_type,
                user_id = self.user.id)

        month_days = calendar.monthrange(datetime.utcnow().year,datetime.utcnow().month)
        start_time = datetime.utcnow().strftime("%Y-%m-01")
        end_time = datetime.utcnow().strftime("%Y-%m-" + str(month_days[1]) )

        self.assertEqual(self.user.uploaded_kilobytes(start_time=start_time, end_time=end_time), 72)
项目:django-billometer    作者:tcpcloud    | 项目源码 | 文件源码
def get_allocation_price(self, resource, name=None, today=None):

        quota = self.get_quota(resource, name)

        if quota == -1:
            return 0

        if today is None:
            today = date.today()

        rate = self.get_rate(resource, name)
        #month_range = calendar.monthrange(today.year, today.month)[1]
        # for variable month days/hours
        #price = decimal.Decimal('0.24') * rate * decimal.Decimal(quota) * decimal.Decimal(month_range)
        # for fixed month days/hours: 730
        price = D('73.0') * rate * decimal.Decimal(quota)

        return price
项目:series-tiempo-ar-api    作者:datosgobar    | 项目源码 | 文件源码
def run(self, query, args):
        self.start = args.get(constants.PARAM_START_DATE)
        self.end = args.get(constants.PARAM_END_DATE)

        self.validate_start_end_dates()
        if self.errors:
            return

        start_date, end_date = None, None
        if self.start:
            start_date = str(iso8601.parse_date(self.start).date())
        if self.end:
            end_date = iso8601.parse_date(self.end).date()
            if '-' not in self.end:  # Solo especifica año
                end_date = datetime.date(end_date.year, 12, 31)
            if self.end.count('-') == 1:  # Especifica año y mes
                # Obtengo el último día del mes, monthrange devuelve
                # tupla (month, last_day)
                days = monthrange(end_date.year, end_date.month)[1]
                end_date = datetime.date(end_date.year, end_date.month, days)

        query.add_filter(start_date, end_date)
项目:nav    作者:UNINETT    | 项目源码 | 文件源码
def get_interval(sometime, interval):
    """Gets the interval for some time

    :param sometime: A datetime.datetime object
    :param interval: A string to indicate interval
    :returns: The start and endtime for the interval
    :rtype: datetime.datetime, datetime.datetime
    """
    year = sometime.year
    month = sometime.month
    if interval == ReportSubscription.MONTH:
        _day, days = calendar.monthrange(year, month)
        start = datetime(year, month, 1)
        end = datetime(year, month, days) + timedelta(days=1)
    elif interval == ReportSubscription.WEEK:
        start = sometime - timedelta(days=sometime.weekday())
        end = start + timedelta(days=7)
    else:
        # interval is one day
        start = sometime
        end = start + timedelta(days=1)
    return start, end
项目:django-nanoCRM    作者:Mrsserj    | 项目源码 | 文件源码
def calendar(request, year=None, month=None):
    customer = None
    if request.GET.has_key('customer_id'):
        customer = Customer.objects.get(pk=request.GET['customer_id'])
    if year is None or month is None:
        start_date = dt.datetime.strptime('%s.%s' %(dt.datetime.now().month, dt.datetime.now().year), '%m.%Y')
    else:
        start_date = dt.datetime.strptime('%s.%s' %(month, year), '%m.%Y')
    offset = start_date.weekday()+cl.monthrange(start_date.year, start_date.month)[1]
    if offset == 28:
        weeks = [0,1,2,3]
    elif offset > 28 and offset < 36:
        weeks = [0,1,2,3,4]
    else:
        weeks = [0,1,2,3,4,5]
    return render(request, 'calendar.html', { 'offset':offset, 'customer':customer, 'prev':(start_date+dt.timedelta(days=-1)), 'next':(start_date+dt.timedelta(days=32)), 
        'cal_date':start_date, 'start_date':start_date.strftime('%m.%Y'), 'weeks':weeks, 'days':[0,1,2,3,4,5,6] })
项目:fantasy-dota-heroes    作者:ThePianoDentist    | 项目源码 | 文件源码
def add_months(sourcedate,months):
    month = sourcedate.month - 1 + months
    year = int(sourcedate.year + month / 12 )
    month = month % 12 + 1
    day = min(sourcedate.day,calendar.monthrange(year,month)[1])
    return datetime.date(year,month,day)
项目:code    作者:ActiveState    | 项目源码 | 文件源码
def __init__(self, month, year, indent_level, indent_style):
        'x.__init__(...) initializes x'
        calendar.setfirstweekday(calendar.SUNDAY)
        matrix = calendar.monthcalendar(year, month)
        self.__table = HTML_Table(len(matrix) + 1, 7, indent_level, indent_style)
        for column, text in enumerate(calendar.day_name[-1:] + calendar.day_name[:-1]):
            self.__table.mutate(0, column, '<b>%s</b>' % text)
        for row, week in enumerate(matrix):
            for column, day in enumerate(week):
                if day:
                    self.__table.mutate(row + 1, column, '<b>%02d</b>\n<hr>\n' % day)
        self.__weekday, self.__alldays = calendar.monthrange(year, month)
        self.__weekday = ((self.__weekday + 1) % 7) + 6
项目:code    作者:ActiveState    | 项目源码 | 文件源码
def next_month(self):
        """Update calendar to show the next month."""
        if self._selection_is_visible: self._clear_selection()

        date = self.datetime(self._year, self._month, 1) + \
            self.timedelta(days=calendar.monthrange(self._year, self._month)[1] + 1)

        self._build_calendar(date.year, date.month) # reconstuct calendar
项目:cloudhealth-client    作者:cloudify-cosmo    | 项目源码 | 文件源码
def _get_yesterdays_date():
    current = date.today()
    current_time = datetime.utcnow()
    if current.day == 1:
        if current_time.hour <= 5:
            return date(current.year, current.month-1, (calendar.monthrange(current.year, current.month-1)[2])).strftime('%Y-%m-%d')
        else:
            return date(current.year, current.month-1, (calendar.monthrange(current.year, current.month-1)[1])).strftime('%Y-%m-%d')
    else:
        if current_time.hour <= 5:
            return date(current.year, current.month, current.day-2).strftime('%Y-%m-%d')
        else:
            return date(current.year, current.month, current.day-1).strftime('%Y-%m-%d')
项目:cloudhealth-client    作者:cloudify-cosmo    | 项目源码 | 文件源码
def _get_last_month():
    current = date.today()
    if current.day == 31:
        return date(current.year, current.month-1, (calendar.monthrange(current.year, current.month-1)[1])).strftime('%Y-%m')
    else:
        return date(current.year, current.month-1, current.day).strftime('%Y-%m')
项目:pyrsss    作者:butala    | 项目源码 | 文件源码
def get_record(omni_path,
               d1,
               d2,
               template='omni_min{year:04d}{month:02d}.asc',
               inclusive=True):
    """
    Gather an OMNI data record spanning *d1* to *d2* and return a
    :class:`PD.DataFrame`. Use file OMNI data record file names
    specified by *template*. If *inclusive*, the range is *d1* to *d2*
    with equality on both bounds.
    """
    df_list = []
    for year in range(d1.year, d2.year + 1):
        for month in range(1, 13):
            date1 = datetime(year, month, 1)
            date2 = date1 + timedelta(days=monthrange(year, month)[1])
            if not (date1 <= d1 <= date2 or date1 <= d2 <= date2):
                continue
            omni_fname = os.path.join(omni_path,
                                      template.format(year=year,
                                                      month=month))
            if not os.path.isfile(omni_fname):
                logger.warning('could not find {} --- skipping'.format(omni_fname))
                continue
            logger.info('parsing {}'.format(omni_fname))
            df_list.append(parse(omni_fname))
    df = PD.concat(df_list)
    if inclusive:
        return df[d1:d2]
    else:
        return df[d1:d2].iloc[:-1]
项目:django-souvenirs    作者:appsembler    | 项目源码 | 文件源码
def nearest_dom(year, month, day):
    """
    Return day adjusted as necessary to fit within the days available in
    year/month. For example:

        nearest_dom(2017, 2, 30)  #=> 28

    """
    return min(calendar.monthrange(year, month)[1], day)
项目:CodingDojo    作者:ComputerSocietyUNB    | 项目源码 | 文件源码
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]
项目:nstock    作者:ybenitezf    | 项目源码 | 文件源码
def __init__(self, year=None, month=None, day=None, hour=None, minute=None,
                 second=None, microsecond=None):
        if isinstance(year, datetime):
            dt = year
            self.year, self.month, self.day = dt.year, dt.month, dt.day
            self.hour, self.minute, self.second = dt.hour, dt.minute, dt.second
            self.microsecond = dt.microsecond
        else:
            if month is not None and (month < 1 or month > 12):
                raise TimeError("month must be in 1..12")

            if day is not None and day < 1:
                raise TimeError("day must be greater than 1")
            if (year is not None and month is not None and day is not None
                and day > calendar.monthrange(year, month)[1]):
                raise TimeError("day is out of range for month")

            if hour is not None and (hour < 0 or hour > 23):
                raise TimeError("hour must be in 0..23")
            if minute is not None and (minute < 0 or minute > 59):
                raise TimeError("minute must be in 0..59")
            if second is not None and (second < 0 or second > 59):
                raise TimeError("second must be in 0..59")
            if microsecond is not None and (microsecond < 0
                                            or microsecond > 999999):
                raise TimeError("microsecond must be in 0..999999")

            self.year, self.month, self.day = year, month, day
            self.hour, self.minute, self.second = hour, minute, second
            self.microsecond = microsecond
项目:nstock    作者:ybenitezf    | 项目源码 | 文件源码
def ceil(self):
        """Returns a ``datetime`` version of this object with all unspecified
        (None) attributes replaced by their highest values.

        This method raises an error if the ``adatetime`` object has no year.

        >>> adt = adatetime(year=2009, month=5)
        >>> adt.floor()
        datetime.datetime(2009, 5, 30, 23, 59, 59, 999999)
        """

        y, m, d, h, mn, s, ms = (self.year, self.month, self.day, self.hour,
                                 self.minute, self.second, self.microsecond)

        if y is None:
            raise ValueError("Date has no year")

        if m is None:
            m = 12
        if d is None:
            d = calendar.monthrange(y, m)[1]
        if h is None:
            h = 23
        if mn is None:
            mn = 59
        if s is None:
            s = 59
        if ms is None:
            ms = 999999
        return datetime(y, m, d, h, mn, s, ms)
项目:ftrack-kredenc-hooks    作者:kredencstudio    | 项目源码 | 文件源码
def getMonth(date):
    first_day = date.replace(day = 1)
    last_day = date.replace(day = calendar.monthrange(date.year, date.month)[1])
    return first_day, last_day
项目:hiwi-stunden    作者:janisstreib    | 项目源码 | 文件源码
def wd_manage_apply(request, month, year, contract):
    c = Contract.objects.get(id=int(contract), user=request.user)
    month = int(month)
    year = int(year)
    firstDayOfMonth = datetime(year, month, 1, 0, 0, 1, 0).weekday()
    daysInMonth = monthrange(year, month)
    workL = WorkLog.objects.get(contract=c, month=month, year=year)
    # First try apply all anual activities
    anuals = c.fixedworkdustactivity_set.all()
    for a in anuals:
        if a.week_day > firstDayOfMonth:
            anualStep = 1 + a.week_day - firstDayOfMonth
        elif a.week_day == firstDayOfMonth:
            anualStep = 1
        else:
            anualStep = 1 + 7 - firstDayOfMonth + a.week_day
        while anualStep <= daysInMonth[1] and workL.calcHours() + a.avg_length <= c.hours:
            wt = WorkTime()
            wt.work_log = workL
            if a.avg_length >= 6:
                wt.pause = 1
            else:
                wt.pause = 0
            wt.begin = datetime(year, month, anualStep, a.start.hour, a.start.minute, 0, 0)
            beginstamp = (wt.begin - datetime(1970, 1, 1)).total_seconds()
            wt.end = datetime.fromtimestamp(beginstamp +
                                            a.avg_length * 60.0*60.0 + wt.pause * 60.0*60.0)
            # wt.end = wt.begin.replace(hour=int(wt.begin.hour + math.floor(a.avg_length) + wt.pause))
            # wt.end = wt.end.replace(minute=int(round((a.avg_length - math.floor(a.avg_length)) * 60)))
            wt.activity = a.description
            wt.clean_fields(year, month)
            wt.save()
            anualStep += 7
    # Then fill with "other" activities
    filler = FillerWorkDustActivity.objects.all()
    largestFreeSlot = 0
    smallestFiller = filler.aggregate(Min('avg_length'))['avg_length__min']

    while not smallestFiller == None and largestFreeSlot >= smallestFiller:
        pass
    return redirect("/?month=" + str(month) + "&year=" + str(year) + "#" + str(c.id))
项目:black-hole    作者:liuhao1024    | 项目源码 | 文件源码
def days_in_month(self):
        """
        ????????
        :return:
        """
        return calendar.monthrange(self.year, self.month)[1]
项目:tianchi_power    作者:lvniqi    | 项目源码 | 文件源码
def get_holiday_df(year,month):
    monthRange = calendar.monthrange(year,month)[-1]
    mask_month = "%s%s"%(year,month)
    if month < 10:
        mask_month = "%s0%s"%(year,month)
    mask = get_holiday_mask(mask_month)
    a = pd.DataFrame(index = pd.date_range('%s-%s-1'%(year,month), periods=monthRange, freq='D'))
    index = pd.Series(a.index)
    mask_df = index.apply(lambda x:mask[x.day] if x.day in mask else 0)
    mask_df.index = index
    a['holiday'] = (mask_df == 1).astype('int')
    a['festday'] = (mask_df == 2).astype('int')
    return a
项目:lagendacommun    作者:ecreall    | 项目源码 | 文件源码
def get_month_range(start_date=None, next_month=False):
    if start_date is None:
        start_date = datetime.date.today()

    month = start_date.month
    year = start_date.year
    if next_month:
        month = 1 if start_date.month == 12 else start_date.month + 1
        if month == 1:
            year += 1

    start_date = start_date.replace(day=1, month=month, year=year)
    _, days_in_month = calendar.monthrange(year, month)
    end_date = start_date + datetime.timedelta(days=days_in_month-1)
    return (start_date, end_date)
项目:financial_life    作者:MartinPyka    | 项目源码 | 文件源码
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
项目:financial_life    作者:MartinPyka    | 项目源码 | 文件源码
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)
项目:financial_life    作者:MartinPyka    | 项目源码 | 文件源码
def get_days_per_year(year):
    # returns the number of days per year
    return 365 if monthrange(year, 2)[1] == 28 else 366

# deprecated, old methods for maniuplating datetime
项目:financial_life    作者:MartinPyka    | 项目源码 | 文件源码
def add_month(start_date, months):
    """ introduces calculation with months """
    new_year = start_date.year + int((start_date.month + months - 1)/12)
    new_month = ((start_date.month + months - 1) % 12) + 1
    new_day = min(start_date.day, monthrange(new_year, new_month)[1])
    new_date = date(new_year, new_month, new_day)
    return new_date
项目:notebooks    作者:fluentpython    | 项目源码 | 文件源码
def list_days_of_month(year, month):
    lastday = calendar.monthrange(year, month)[1]
    days = [format_date(year, month, day) for day in range(1, lastday + 1)]
    return days