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

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

项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda    作者:SignalMedia    | 项目源码 | 文件源码
def _validate_time(self, t_input):
        from datetime import time as dt_time
        import time
        if isinstance(t_input, compat.string_types):
            try:
                t = time.strptime(t_input, '%H:%M')
                return dt_time(hour=t.tm_hour, minute=t.tm_min)
            except ValueError:
                raise ValueError("time data must match '%H:%M' format")
        elif isinstance(t_input, dt_time):
            if t_input.second != 0 or t_input.microsecond != 0:
                raise ValueError(
                    "time data must be specified only with hour and minute")
            return t_input
        else:
            raise ValueError("time data must be string or datetime.time")
项目: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, 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
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda    作者:SignalMedia    | 项目源码 | 文件源码
def _is_normalized(dt):
    if (dt.hour != 0 or dt.minute != 0 or dt.second != 0 or
            dt.microsecond != 0 or getattr(dt, 'nanosecond', 0) != 0):
        return False
    return True

# ---------------------------------------------------------------------
# DateOffset
项目: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 _get_business_hours_by_sec(self):
        """
        Return business hours in a day by seconds.
        """
        if self._get_daytime_flag():
            # create dummy datetime to calcurate businesshours in a day
            dtstart = datetime(2014, 4, 1, self.start.hour, self.start.minute)
            until = datetime(2014, 4, 1, self.end.hour, self.end.minute)
            return tslib.tot_seconds(until - dtstart)
        else:
            self.daytime = False
            dtstart = datetime(2014, 4, 1, self.start.hour, self.start.minute)
            until = datetime(2014, 4, 2, self.end.hour, self.end.minute)
            return tslib.tot_seconds(until - dtstart)
项目: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, days_in_month = tslib.monthrange(other.year, self.month)
        lastBDay = (days_in_month -
                    max(((wkday + days_in_month - 1) % 7) - 4, 0))

        years = n
        if n > 0:
            if (other.month < self.month or
                    (other.month == self.month and other.day < lastBDay)):
                years -= 1
        elif n <= 0:
            if (other.month > self.month or
                    (other.month == self.month and other.day > lastBDay)):
                years += 1

        other = other + relativedelta(years=years)

        _, days_in_month = tslib.monthrange(other.year, self.month)
        result = datetime(other.year, self.month, days_in_month,
                          other.hour, other.minute, other.second,
                          other.microsecond)

        if result.weekday() > 4:
            result = result - BDay()

        return result
项目: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
项目:Chromium_DepotTools    作者:p07r0457    | 项目源码 | 文件源码
def totime(somedate):
    """return a time from a time (leaving unchanged), date or datetime"""
    # XXX mx compat
    if not isinstance(somedate, time):
        return time(somedate.hour, somedate.minute, somedate.second)
    assert isinstance(somedate, (time)), repr(somedate)
    return somedate
项目:Chromium_DepotTools    作者:p07r0457    | 项目源码 | 文件源码
def ustrftime(somedate, fmt='%Y-%m-%d'):
    """like strftime, but returns a unicode string instead of an encoded
    string which may be problematic with localized date.
    """
    if sys.version_info >= (3, 3):
        # datetime.date.strftime() supports dates since year 1 in Python >=3.3.
        return somedate.strftime(fmt)
    else:
        try:
            if sys.version_info < (3, 0):
                encoding = getlocale(LC_TIME)[1] or 'ascii'
                return unicode(somedate.strftime(str(fmt)), encoding)
            else:
                return somedate.strftime(fmt)
        except ValueError:
            if somedate.year >= 1900:
                raise
            # datetime is not happy with dates before 1900
            # we try to work around this, assuming a simple
            # format string
            fields = {'Y': somedate.year,
                      'm': somedate.month,
                      'd': somedate.day,
                      }
            if isinstance(somedate, datetime):
                fields.update({'H': somedate.hour,
                               'M': somedate.minute,
                               'S': somedate.second})
            fmt = re.sub('%([YmdHMS])', r'%(\1)02d', fmt)
            return unicode(fmt) % fields
项目:node-gn    作者:Shouqun    | 项目源码 | 文件源码
def totime(somedate):
    """return a time from a time (leaving unchanged), date or datetime"""
    # XXX mx compat
    if not isinstance(somedate, time):
        return time(somedate.hour, somedate.minute, somedate.second)
    assert isinstance(somedate, (time)), repr(somedate)
    return somedate
项目:node-gn    作者:Shouqun    | 项目源码 | 文件源码
def ustrftime(somedate, fmt='%Y-%m-%d'):
    """like strftime, but returns a unicode string instead of an encoded
    string which may be problematic with localized date.
    """
    if sys.version_info >= (3, 3):
        # datetime.date.strftime() supports dates since year 1 in Python >=3.3.
        return somedate.strftime(fmt)
    else:
        try:
            if sys.version_info < (3, 0):
                encoding = getlocale(LC_TIME)[1] or 'ascii'
                return unicode(somedate.strftime(str(fmt)), encoding)
            else:
                return somedate.strftime(fmt)
        except ValueError:
            if somedate.year >= 1900:
                raise
            # datetime is not happy with dates before 1900
            # we try to work around this, assuming a simple
            # format string
            fields = {'Y': somedate.year,
                      'm': somedate.month,
                      'd': somedate.day,
                      }
            if isinstance(somedate, datetime):
                fields.update({'H': somedate.hour,
                               'M': somedate.minute,
                               'S': somedate.second})
            fmt = re.sub('%([YmdHMS])', r'%(\1)02d', fmt)
            return unicode(fmt) % fields
项目:depot_tools    作者:webrtc-uwp    | 项目源码 | 文件源码
def totime(somedate):
    """return a time from a time (leaving unchanged), date or datetime"""
    # XXX mx compat
    if not isinstance(somedate, time):
        return time(somedate.hour, somedate.minute, somedate.second)
    assert isinstance(somedate, (time)), repr(somedate)
    return somedate
项目:depot_tools    作者:webrtc-uwp    | 项目源码 | 文件源码
def ustrftime(somedate, fmt='%Y-%m-%d'):
    """like strftime, but returns a unicode string instead of an encoded
    string which may be problematic with localized date.
    """
    if sys.version_info >= (3, 3):
        # datetime.date.strftime() supports dates since year 1 in Python >=3.3.
        return somedate.strftime(fmt)
    else:
        try:
            if sys.version_info < (3, 0):
                encoding = getlocale(LC_TIME)[1] or 'ascii'
                return unicode(somedate.strftime(str(fmt)), encoding)
            else:
                return somedate.strftime(fmt)
        except ValueError:
            if somedate.year >= 1900:
                raise
            # datetime is not happy with dates before 1900
            # we try to work around this, assuming a simple
            # format string
            fields = {'Y': somedate.year,
                      'm': somedate.month,
                      'd': somedate.day,
                      }
            if isinstance(somedate, datetime):
                fields.update({'H': somedate.hour,
                               'M': somedate.minute,
                               'S': somedate.second})
            fmt = re.sub('%([YmdHMS])', r'%(\1)02d', fmt)
            return unicode(fmt) % fields
项目:wuye.vim    作者:zhaoyingnan911    | 项目源码 | 文件源码
def totime(somedate):
    """return a time from a time (leaving unchanged), date or datetime"""
    # XXX mx compat
    if not isinstance(somedate, time):
        return time(somedate.hour, somedate.minute, somedate.second)
    assert isinstance(somedate, (time)), repr(somedate)
    return somedate
项目:wuye.vim    作者:zhaoyingnan911    | 项目源码 | 文件源码
def ustrftime(somedate, fmt='%Y-%m-%d'):
    """like strftime, but returns a unicode string instead of an encoded
    string which may be problematic with localized date.
    """
    if sys.version_info >= (3, 3):
        # datetime.date.strftime() supports dates since year 1 in Python >=3.3.
        return somedate.strftime(fmt)
    else:
        try:
            if sys.version_info < (3, 0):
                encoding = getlocale(LC_TIME)[1] or 'ascii'
                return unicode(somedate.strftime(str(fmt)), encoding)
            else:
                return somedate.strftime(fmt)
        except ValueError:
            if somedate.year >= 1900:
                raise
            # datetime is not happy with dates before 1900
            # we try to work around this, assuming a simple
            # format string
            fields = {'Y': somedate.year,
                      'm': somedate.month,
                      'd': somedate.day,
                      }
            if isinstance(somedate, datetime):
                fields.update({'H': somedate.hour,
                               'M': somedate.minute,
                               'S': somedate.second})
            fmt = re.sub('%([YmdHMS])', r'%(\1)02d', fmt)
            return unicode(fmt) % fields
项目: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