Python datetime.date 模块,year() 实例源码

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

项目:tuxbot-bot    作者:outout14    | 项目源码 | 文件源码
def ci_register(self, ctx):
        cursor.execute("""SELECT id, userid FROM users WHERE userid=?""", (ctx.message.author.id,))
        existansw = cursor.fetchone()
        if existansw != None:
            await ctx.send("Mais tu as déja une carte d'identité ! u_u")
        else:
            date = datetime.datetime.now()

            nd = str(date.day)
            nd += "-"
            nd += str(date.month)
            nd += "-"
            nd += str(date.year)

            cursor.execute("""INSERT INTO users(userid, username, useravatar, userbirth, cidate, cibureau) VALUES(?, ?, ?, ?, ?, ?)""", (ctx.message.author.id, ctx.message.author.name,  ctx.message.author.avatar_url, ctx.message.author.created_at, nd, str(ctx.message.guild.name)))
            conn.commit()
            await ctx.send(":clap: Bievenue à toi {} dans le communisme {} ! Fait ``.ci`` pour plus d'informations !".format(ctx.message.author.name, str(ctx.message.guild.name)))
项目:My-Web-Server-Framework-With-Python2.7    作者:syjsu    | 项目源码 | 文件源码
def Date(self, year, month, day):
        """
        Returns an object representing the specified date.

        This method is equivalent to the module-level ``Date()`` method in
        an underlying DB API-compliant module.

        :Parameters:
            year
                the year
            month
                the month
            day
                the day of the month

        :return: an object containing the date
        """
        return self.__driver.get_import().Date(year, month, day)
项目:My-Web-Server-Framework-With-Python2.7    作者:syjsu    | 项目源码 | 文件源码
def DateFromTicks(self, secs):
        """
        Returns an object representing the date *secs* seconds after the
        epoch. For example:

        .. python::

            import time

            d = db.DateFromTicks(time.time())

        This method is equivalent to the module-level ``DateFromTicks()``
        method in an underlying DB API-compliant module.

        :Parameters:
            secs : int
                the seconds from the epoch

        :return: an object containing the date
        """
        date = date.fromtimestamp(secs)
        return self.__driver.get_import().Date(date.year, date.month, date.day)
项目:My-Web-Server-Framework-With-Python2.7    作者:syjsu    | 项目源码 | 文件源码
def Timestamp(self, year, month, day, hour, minute, second):
        """
        Returns an object representing the specified time.

        This method is equivalent to the module-level ``Timestamp()`` method
        in an underlying DB API-compliant module.

        :Parameters:
            year
                the year
            month
                the month
            day
                the day of the month
            hour
                the hour of the day
            minute
                the minute within the hour. 0 <= *minute* <= 59
            second
                the second within the minute. 0 <= *second* <= 59

        :return: an object containing the timestamp
        """
        return self.__driver.get_import().Timestamp(year, month, day,
                                                    hour, minute, second)
项目:My-Web-Server-Framework-With-Python2.7    作者:syjsu    | 项目源码 | 文件源码
def TimestampFromTicks(self, secs):
        """
        Returns an object representing the date and time ``secs`` seconds
        after the epoch. For example:

        .. python::

            import time

            d = db.TimestampFromTicks(time.time())

        This method is equivalent to the module-level ``TimestampFromTicks()``
        method in an underlying DB API-compliant module.

        :Parameters:
            secs : int
                the seconds from the epoch

        :return: an object containing the timestamp
        """
        dt = datetime.now()
        return self.__driver.get_import().Timestamp(dt.year, dt.month, dt.day,
                                                    dt.hour, dt.minute, dt.second)
项目:mr_meeseeks    作者:garr741    | 项目源码 | 文件源码
def getEvents(self, channel):
      url = "https://www.googleapis.com/calendar/v3/calendars/" + calendarId + "/events/?key=" + apiKey
      results = requests.get(url)
      i = 0
      nextEvents = []
      for n in results.json()["items"]:
        if n["status"] == "confirmed":
          theDate = ""
          checker = date.today() - timedelta(1)
          yesterday = datetime(checker.year, checker.month, checker.day)
          try:
            theDate = parse(n["start"]["dateTime"])
            if datetime(theDate.year, theDate.month, theDate.day) > yesterday:
              nextEvents.append(n)
          except Exception as e:
            theDate = parse(n["start"]["date"])
            if datetime(theDate.year, theDate.month, theDate.day) > yesterday:
              nextEvents.append(n)
      return nextEvents
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda    作者:SignalMedia    | 项目源码 | 文件源码
def _next_opening_time(self, other):
        """
        If n is positive, return tomorrow's business day opening time.
        Otherwise yesterday's business day's opening time.

        Opening time always locates on BusinessDay.
        Otherwise, closing time may not if business hour extends over midnight.
        """
        if not self.next_bday.onOffset(other):
            other = other + self.next_bday
        else:
            if self.n >= 0 and self.start < other.time():
                other = other + self.next_bday
            elif self.n < 0 and other.time() < self.start:
                other = other + self.next_bday
        return datetime(other.year, other.month, other.day,
                        self.start.hour, self.start.minute)
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda    作者:SignalMedia    | 项目源码 | 文件源码
def apply(self, other):
        n = self.n
        wkday, _ = tslib.monthrange(other.year, other.month)
        first = _get_firstbday(wkday)

        if other.day > first and n <= 0:
            # as if rolled forward already
            n += 1
        elif other.day < first and n > 0:
            other = other + timedelta(days=first - other.day)
            n -= 1

        other = other + relativedelta(months=n)
        wkday, _ = tslib.monthrange(other.year, other.month)
        first = _get_firstbday(wkday)
        result = datetime(other.year, other.month, first,
                          other.hour, other.minute,
                          other.second, other.microsecond)
        return result
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda    作者:SignalMedia    | 项目源码 | 文件源码
def apply(self, other):
        base = other
        if self.weekday is None:
            return other + self.n * self._inc

        if self.n > 0:
            k = self.n
            otherDay = other.weekday()
            if otherDay != self.weekday:
                other = other + timedelta((self.weekday - otherDay) % 7)
                k = k - 1
            other = other
            for i in range(k):
                other = other + self._inc
        else:
            k = self.n
            otherDay = other.weekday()
            if otherDay != self.weekday:
                other = other + timedelta((self.weekday - otherDay) % 7)
            for i in range(-k):
                other = other - self._inc

        other = datetime(other.year, other.month, other.day,
                         base.hour, base.minute, base.second, base.microsecond)
        return other
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda    作者:SignalMedia    | 项目源码 | 文件源码
def apply(self, other):
        base = other
        offsetOfMonth = self.getOffsetOfMonth(other)

        if offsetOfMonth > other:
            if self.n > 0:
                months = self.n - 1
            else:
                months = self.n
        elif offsetOfMonth == other:
            months = self.n
        else:
            if self.n > 0:
                months = self.n
            else:
                months = self.n + 1

        other = self.getOffsetOfMonth(
            other + relativedelta(months=months, day=1))
        other = datetime(other.year, other.month, other.day, base.hour,
                         base.minute, base.second, base.microsecond)
        return other
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda    作者:SignalMedia    | 项目源码 | 文件源码
def apply(self, other):
        n = self.n
        base = other
        other = datetime(other.year, other.month, other.day,
                         other.hour, other.minute, other.second,
                         other.microsecond)

        wkday, days_in_month = tslib.monthrange(other.year, other.month)
        lastBDay = days_in_month - max(((wkday + days_in_month - 1)
                                        % 7) - 4, 0)

        monthsToGo = 3 - ((other.month - self.startingMonth) % 3)
        if monthsToGo == 3:
            monthsToGo = 0

        if n > 0 and not (other.day >= lastBDay and monthsToGo == 0):
            n = n - 1
        elif n <= 0 and other.day > lastBDay and monthsToGo == 0:
            n = n + 1

        other = other + relativedelta(months=monthsToGo + 3 * n, day=31)
        other = tslib._localize_pydatetime(other, base.tzinfo)
        if other.weekday() > 4:
            other = other - BDay()
        return other
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda    作者:SignalMedia    | 项目源码 | 文件源码
def apply(self, other):
        n = self.n
        other = datetime(other.year, other.month, other.day,
                         other.hour, other.minute, other.second,
                         other.microsecond)
        wkday, days_in_month = tslib.monthrange(other.year, other.month)

        monthsToGo = 3 - ((other.month - self.startingMonth) % 3)
        if monthsToGo == 3:
            monthsToGo = 0

        if n > 0 and not (other.day >= days_in_month and monthsToGo == 0):
            n = n - 1

        other = other + relativedelta(months=monthsToGo + 3 * n, day=31)
        return other
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda    作者:SignalMedia    | 项目源码 | 文件源码
def apply(self, other):
        n = self.n
        wkday, days_in_month = tslib.monthrange(other.year, other.month)

        monthsSince = (other.month - self.startingMonth) % 3

        if n <= 0 and monthsSince != 0:
            # make sure you roll forward, so negate
            monthsSince = monthsSince - 3

        if n <= 0 and (monthsSince == 0 and other.day > 1):
            # after start, so come back an extra period as if rolled forward
            n = n + 1

        other = other + relativedelta(months=3 * n - monthsSince, day=1)
        return other
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda    作者:SignalMedia    | 项目源码 | 文件源码
def apply(self, other):
        n = self.n
        wkday, days_in_month = tslib.monthrange(other.year, self.month)

        first = _get_firstbday(wkday)

        years = n

        if n > 0:  # roll back first for positive n
            if (other.month < self.month or
                    (other.month == self.month and other.day < first)):
                years -= 1
        elif n <= 0:  # roll forward
            if (other.month > self.month or
                    (other.month == self.month and other.day > first)):
                years += 1

        # set first bday for result
        other = other + relativedelta(years=years)
        wkday, days_in_month = tslib.monthrange(other.year, self.month)
        first = _get_firstbday(wkday)
        return datetime(other.year, self.month, first, other.hour,
                        other.minute, other.second, other.microsecond)
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda    作者:SignalMedia    | 项目源码 | 文件源码
def apply(self, other):
        currentEaster = easter(other.year)
        currentEaster = datetime(
            currentEaster.year, currentEaster.month, currentEaster.day)
        currentEaster = tslib._localize_pydatetime(currentEaster, other.tzinfo)

        # NOTE: easter returns a datetime.date so we have to convert to type of
        # other
        if self.n >= 0:
            if other >= currentEaster:
                new = easter(other.year + self.n)
            else:
                new = easter(other.year + self.n - 1)
        else:
            if other > currentEaster:
                new = easter(other.year + self.n + 1)
            else:
                new = easter(other.year + self.n)

        new = datetime(new.year, new.month, new.day, other.hour,
                       other.minute, other.second, other.microsecond)
        return new
项目:Odysseus    作者:OdysseusDev    | 项目源码 | 文件源码
def user(entity, user, reason=None):
            data = Blacklist.load()
            data["users"][entity] = {"reason":reason,
                                     "by": user,
                                     "on": "{}/{}/{}".format(year, month, day)}
            Blacklist.write(data)
项目:Odysseus    作者:OdysseusDev    | 项目源码 | 文件源码
def channel(entity, user, reason=None):
            data = Blacklist.load()
            data["channels"][entity] = {"reason":reason,
                                        "by": user,
                                        "on": "{}/{}/{}".format(year,
                                                                month,
                                                                day)}
            Blacklist.write(data)
项目:Odysseus    作者:OdysseusDev    | 项目源码 | 文件源码
def guild(entity, user, reason=None):
            data = Blacklist.load()
            data["guilds"][entity] = {"reason":reason,
                                      "by": user,
                                      "on": "{}/{}/{}".format(year, month, day)}
            Blacklist.write(data)
项目:valleyjudge    作者:dcolascione    | 项目源码 | 文件源码
def calculate_take_home_pay(self, date, raw_pay):
        """Return take-home pay on a date given raw pay."""
        assert date in self.__income_dates, date
        year_income = sum(self.__income_by_year[date.year].values())
        year_tax = self.__tax_by_year[date.year]
        taxed_pay = raw_pay - (raw_pay / year_income) * year_tax
        return taxed_pay
项目:valleyjudge    作者:dcolascione    | 项目源码 | 文件源码
def __init__(self,
                 *,
                 total,
                 start = None,
                 vesting_dates = DEFAULT_VESTING_DATES,
                 vesting = (0.25, 0.25, 0.25, 0.25)):
        """Create an equity grant description.

        TOTAL is the total size, in dollars, of the grant.  START is
        the date on which it starts; if None, the grant clock starts
        on the company start date.  VESTING_DATES is a sequence of
        (MONTH, DAY) pairs on which equity grants vest --- a grant
        that vests quarterly will have a four-element
        VESTING_DATES sequence.

        VESTING is a sequence of numbers that sum to 1.0.  With default
        vesting dates, each one represents a year over which the grant vests, 
        and the value of the number indicates the portion of the grant that 
        vests in that year.

        """
        self.total = typecheck(total, numbers.Real)
        self.start = typecheck(start, (date, timedelta, type(None)))
        self.vesting_dates = typecheck(vesting_dates, seq_of(pair_of(int)))
        self.vesting = typecheck(vesting, seq_of(numbers.Real))
        if not math.isclose(sum(vesting), 1.0, rel_tol=1e-5):
            raise ValueError("vesting fractions do not sum to 1: %1.5f" % sum(vesting))
项目:valleyjudge    作者:dcolascione    | 项目源码 | 文件源码
def make_vests(
        total,
        annual_ratios,
        start_date,
        vesting_dates):
    """Generate a vesting schedule for a grant.

    TOTAL is the total value, in dollars, of the grant.  ANNUAL_RATIOS
    is a sequence of numbers, which must sum to one, that determine
    how much of the grant vests in each year.  START_DATE is a
    datetime.date object indicating when the grant clock starts
    ticking.  VESTING_DATES is a sequence of (MONTH, DAY) tuples that
    indicate the months and days when grants vest each year.

    Return a sequence of (VDATE, VAMOUNT) tuples; each VDATE is a date
    on which a vest happens; and VAMOUNT is the amount, in dollars,
    given out on that day.

    """
    vests = []
    cliff_vest_day = start_date.replace(year = start_date.year + 1)
    vests.append((cliff_vest_day, annual_ratios[0] * total))
    annual_ratios = annual_ratios[1:]
    nrv = 0
    d = cliff_vest_day + timedelta(days=1)
    while annual_ratios:
        if (d.month, d.day) in vesting_dates:
            dist_from_cliff = d - cliff_vest_day
            frac = annual_ratios[0] / len(vesting_dates)
            vests.append((d, frac * total))
            nrv += 1
        if nrv == len(vesting_dates):
            nrv = 0
            annual_ratios = annual_ratios[1:]
        d += timedelta(days=1)
    return vests
项目:tuxbot-bot    作者:outout14    | 项目源码 | 文件源码
def test(self, ctx):

        date = datetime.datetime.now()

        nd = str(date.day)
        nd += "-"
        nd += str(date.month)
        nd += "-"
        nd += str(date.year)

        await ctx.send(nd)
项目:mr_meeseeks    作者:garr741    | 项目源码 | 文件源码
def dateFormatter(self, date):
      month = calendar.month_name[date.month]
      weekday = calendar.day_name[date.weekday()]
      day = date.day
      year = date.year
      results = str(weekday) + ", " + str(month) + " " + str(day) + ", " + str(year)
      return results
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda    作者:SignalMedia    | 项目源码 | 文件源码
def _prev_opening_time(self, other):
        """
        If n is positive, return yesterday's business day opening time.
        Otherwise yesterday business day's opening time.
        """
        if not self.next_bday.onOffset(other):
            other = other - self.next_bday
        else:
            if self.n >= 0 and other.time() < self.start:
                other = other - self.next_bday
            elif self.n < 0 and other.time() > self.start:
                other = other - self.next_bday
        return datetime(other.year, other.month, other.day,
                        self.start.hour, self.start.minute)
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda    作者:SignalMedia    | 项目源码 | 文件源码
def onOffset(self, dt):
        if self.normalize and not _is_normalized(dt):
            return False

        if dt.tzinfo is not None:
            dt = datetime(dt.year, dt.month, dt.day, dt.hour,
                          dt.minute, dt.second, dt.microsecond)
        # Valid BH can be on the different BusinessDay during midnight
        # Distinguish by the time spent from previous opening time
        businesshours = self._get_business_hours_by_sec()
        return self._onOffset(dt, businesshours)
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda    作者:SignalMedia    | 项目源码 | 文件源码
def apply(self, other):
        n = self.n
        _, days_in_month = tslib.monthrange(other.year, other.month)
        if other.day != days_in_month:
            other = other + relativedelta(months=-1, day=31)
            if n <= 0:
                n = n + 1
        other = other + relativedelta(months=n, day=31)
        return other
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda    作者:SignalMedia    | 项目源码 | 文件源码
def onOffset(self, dt):
        if self.normalize and not _is_normalized(dt):
            return False
        days_in_month = tslib.monthrange(dt.year, dt.month)[1]
        return dt.day == days_in_month
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda    作者:SignalMedia    | 项目源码 | 文件源码
def onOffset(self, dt):
        if self.normalize and not _is_normalized(dt):
            return False
        first_weekday, _ = tslib.monthrange(dt.year, dt.month)
        if first_weekday == 5:
            return dt.day == 3
        elif first_weekday == 6:
            return dt.day == 2
        else:
            return dt.day == 1
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda    作者:SignalMedia    | 项目源码 | 文件源码
def getOffsetOfMonth(self, dt):
        w = Week(weekday=self.weekday)
        d = datetime(dt.year, dt.month, 1, tzinfo=dt.tzinfo)
        d = w.rollforward(d)

        for i in range(self.week):
            d = w.apply(d)

        return d
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda    作者:SignalMedia    | 项目源码 | 文件源码
def getOffsetOfMonth(self, dt):
        m = MonthEnd()
        d = datetime(dt.year, dt.month, 1, dt.hour, dt.minute,
                     dt.second, dt.microsecond, tzinfo=dt.tzinfo)
        eom = m.rollforward(d)
        w = Week(weekday=self.weekday)
        return w.rollback(eom)
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda    作者:SignalMedia    | 项目源码 | 文件源码
def apply(self, other):
        n = self.n
        wkday, _ = tslib.monthrange(other.year, other.month)

        first = _get_firstbday(wkday)

        monthsSince = (other.month - self.startingMonth) % 3

        if n <= 0 and monthsSince != 0:  # make sure to roll forward so negate
            monthsSince = monthsSince - 3

        # roll forward if on same month later than first bday
        if n <= 0 and (monthsSince == 0 and other.day > first):
            n = n + 1
        # pretend to roll back if on same month but before firstbday
        elif n > 0 and (monthsSince == 0 and other.day < first):
            n = n - 1

        # get the first bday for result
        other = other + relativedelta(months=3 * n - monthsSince)
        wkday, _ = tslib.monthrange(other.year, other.month)
        first = _get_firstbday(wkday)
        result = datetime(other.year, other.month, first,
                          other.hour, other.minute, other.second,
                          other.microsecond)
        return result
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda    作者:SignalMedia    | 项目源码 | 文件源码
def onOffset(self, dt):
        if self.normalize and not _is_normalized(dt):
            return False
        wkday, days_in_month = tslib.monthrange(dt.year, self.month)
        return self.month == dt.month and dt.day == days_in_month
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda    作者:SignalMedia    | 项目源码 | 文件源码
def apply(self, other):
        def _increment(date, n):
            year = date.year + n - 1
            if date.month >= self.month:
                year += 1
            return datetime(year, self.month, 1, date.hour, date.minute,
                            date.second, date.microsecond)

        def _decrement(date, n):
            year = date.year + n + 1
            if date.month < self.month or (date.month == self.month and
                                           date.day == 1):
                year -= 1
            return datetime(year, self.month, 1, date.hour, date.minute,
                            date.second, date.microsecond)

        def _rollf(date):
            if (date.month != self.month) or date.day > 1:
                date = _increment(date, 1)
            return date

        n = self.n
        result = other
        if n > 0:
            result = _increment(result, n)
        elif n < 0:
            result = _decrement(result, n)
        else:
            # n == 0, roll forward
            result = _rollf(result)
        return result
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda    作者:SignalMedia    | 项目源码 | 文件源码
def onOffset(self, dt):
        if self.normalize and not _is_normalized(dt):
            return False
        dt = datetime(dt.year, dt.month, dt.day)
        year_end = self.get_year_end(dt)

        if self.variation == "nearest":
            # We have to check the year end of "this" cal year AND the previous
            return year_end == dt or \
                self.get_year_end(dt - relativedelta(months=1)) == dt
        else:
            return year_end == dt
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda    作者:SignalMedia    | 项目源码 | 文件源码
def _get_year_end_last(self, dt):
        current_year = datetime(
            dt.year, self.startingMonth, 1, tzinfo=dt.tzinfo)
        return current_year + self._offset_lwom
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda    作者:SignalMedia    | 项目源码 | 文件源码
def apply(self, other):
        base = other
        n = self.n

        if n > 0:
            while n > 0:
                if not self._offset.onOffset(other):
                    qtr_lens = self.get_weeks(other)
                    start = other - self._offset
                else:
                    start = other
                    qtr_lens = self.get_weeks(other + self._offset)

                for weeks in qtr_lens:
                    start += relativedelta(weeks=weeks)
                    if start > other:
                        other = start
                        n -= 1
                        break

        else:
            n = -n
            while n > 0:
                if not self._offset.onOffset(other):
                    qtr_lens = self.get_weeks(other)
                    end = other + self._offset
                else:
                    end = other
                    qtr_lens = self.get_weeks(other)

                for weeks in reversed(qtr_lens):
                    end -= relativedelta(weeks=weeks)
                    if end < other:
                        other = end
                        n -= 1
                        break
        other = datetime(other.year, other.month, other.day,
                         base.hour, base.minute, base.second, base.microsecond)
        return other
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda    作者:SignalMedia    | 项目源码 | 文件源码
def onOffset(self, dt):
        if self.normalize and not _is_normalized(dt):
            return False
        return date(dt.year, dt.month, dt.day) == easter(dt.year)

# ---------------------------------------------------------------------
# Ticks
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda    作者:SignalMedia    | 项目源码 | 文件源码
def _get_firstbday(wkday):
    """
    wkday is the result of monthrange(year, month)

    If it's a saturday or sunday, increment first business day to reflect this
    """
    first = 1
    if wkday == 5:  # on Saturday
        first = 3
    elif wkday == 6:  # on Sunday
        first = 2
    return first
项目:kisqpy    作者:pkulev    | 项目源码 | 文件源码
def from_datetime(date):
    """Return QDate object from datetime.date."""

    return QDate(date.year, date.month, date.day)
项目:kisqpy    作者:pkulev    | 项目源码 | 文件源码
def to_datetime(qdate):
    """Return datetime.date object from QDate."""

    return date(day=qdate.day(), month=qdate.month(), year=qdate.year())
项目:forest-django    作者:ForestAdmin    | 项目源码 | 文件源码
def _get_custom_select(params):
    select = {}
    group_by_date_field = params.get('group_by_date_field')
    time_range = params.get('time_range')
    if time_range == 'Day':
        select['day'] = 'date(%s)' % group_by_date_field
    elif time_range == 'Month':
        select['month'] = "extract(month FROM %s)" % group_by_date_field
        select['year'] = "extract(year FROM %s)" % group_by_date_field
    elif time_range == 'Year':
        select['year'] = "extract(year FROM %s)" % group_by_date_field
    elif time_range == 'Week':
        select['week'] = "date_trunc('week', %s)" % group_by_date_field

    return select
项目:forest-django    作者:ForestAdmin    | 项目源码 | 文件源码
def _format_data(data, params):
    time_range = params.get('time_range')
    day = 1
    month = 1

    for item in data:
        if time_range == 'Day':
            date = item.pop('day')
            day = date.day
            month = date.month
            year = date.year
        elif time_range == 'Month':
            month = int(item.pop('month'))
            year = int(item.pop('year'))
        elif time_range == 'Year':
            year = int(item.pop('year'))
        elif time_range == 'Week':
            date = item.pop('week')
            day = date.day
            month = date.month
            year = date.year

        item['label'] = "%d-%02d-%02d" % (year, month, day)
        item['values'] = { 'value': item.pop('value') }

    _sort_data_by_date(data)
    _fill_empty_date(data, params)
项目:ccvpn3    作者:CCrypto    | 项目源码 | 文件源码
def monthdelta(date, delta):
    m = (date.month + delta) % 12
    y = date.year + (date.month + delta - 1) // 12
    if not m:
        m = 12
    d = min(date.day, [31, 29 if y % 4 == 0 and not y % 400 == 0
                       else 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
                       ][m - 1])
    return date.replace(day=d, month=m, year=y)
项目:ccvpn3    作者:CCrypto    | 项目源码 | 文件源码
def time_filter_between(period, m, df):
    def _filter(o):
        if period == 'm':
            return df(o).year == m.year and df(o).month == m.month and df(o).day == m.day
            return df(o).date() <= m and df(o).date() > (m - timedelta(days=1))
        if period == 'y':
            return df(o).year == m.year and df(o).month == m.month
            return (df(o).date().replace(day=1) <= m and
                    df(o).date().replace(day=1) > (m - timedelta(days=30)))
    return _filter
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda    作者:SignalMedia    | 项目源码 | 文件源码
def apply(self, other):
        def _increment(date):
            if date.month == self.month:
                _, days_in_month = tslib.monthrange(date.year, self.month)
                if date.day != days_in_month:
                    year = date.year
                else:
                    year = date.year + 1
            elif date.month < self.month:
                year = date.year
            else:
                year = date.year + 1
            _, days_in_month = tslib.monthrange(year, self.month)
            return datetime(year, self.month, days_in_month,
                            date.hour, date.minute, date.second,
                            date.microsecond)

        def _decrement(date):
            year = date.year if date.month > self.month else date.year - 1
            _, days_in_month = tslib.monthrange(year, self.month)
            return datetime(year, self.month, days_in_month,
                            date.hour, date.minute, date.second,
                            date.microsecond)

        def _rollf(date):
            if date.month != self.month or\
               date.day < tslib.monthrange(date.year, date.month)[1]:
                date = _increment(date)
            return date

        n = self.n
        result = other
        if n > 0:
            while n > 0:
                result = _increment(result)
                n -= 1
        elif n < 0:
            while n < 0:
                result = _decrement(result)
                n += 1
        else:
            # n == 0, roll forward
            result = _rollf(result)
        return result