當前位置: 首頁>>代碼示例>>Python>>正文


Python datetime.time方法代碼示例

本文整理匯總了Python中datetime.datetime.time方法的典型用法代碼示例。如果您正苦於以下問題:Python datetime.time方法的具體用法?Python datetime.time怎麽用?Python datetime.time使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在datetime.datetime的用法示例。


在下文中一共展示了datetime.time方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: _pre_TIMESTAMP_LTZ_to_python

# 需要導入模塊: from datetime import datetime [as 別名]
# 或者: from datetime.datetime import time [as 別名]
def _pre_TIMESTAMP_LTZ_to_python(self, value, ctx) -> datetime:
        """Converts TIMESTAMP LTZ to datetime.

        This takes consideration of the session parameter TIMEZONE if available. If not, tzlocal is used.
        """
        microseconds, fraction_of_nanoseconds = _extract_timestamp(value, ctx)
        tzinfo_value = self._get_session_tz()

        try:
            t0 = ZERO_EPOCH + timedelta(seconds=microseconds)
            t = pytz.utc.localize(t0, is_dst=False).astimezone(tzinfo_value)
            return t, fraction_of_nanoseconds
        except OverflowError:
            logger.debug(
                "OverflowError in converting from epoch time to "
                "timestamp_ltz: %s(ms). Falling back to use struct_time."
            )
            return time.localtime(microseconds), fraction_of_nanoseconds 
開發者ID:snowflakedb,項目名稱:snowflake-connector-python,代碼行數:20,代碼來源:converter.py

示例2: parse_tzstr

# 需要導入模塊: from datetime import datetime [as 別名]
# 或者: from datetime.datetime import time [as 別名]
def parse_tzstr(self, tzstr, zero_as_utc=True):
        """
        Parse a valid ISO time zone string.

        See :func:`isoparser.isoparse` for details on supported formats.

        :param tzstr:
            A string representing an ISO time zone offset

        :param zero_as_utc:
            Whether to return :class:`dateutil.tz.tzutc` for zero-offset zones

        :return:
            Returns :class:`dateutil.tz.tzoffset` for offsets and
            :class:`dateutil.tz.tzutc` for ``Z`` and (if ``zero_as_utc`` is
            specified) offsets equivalent to UTC.
        """
        return self._parse_tzstr(tzstr, zero_as_utc=zero_as_utc)

    # Constants 
開發者ID:MediaBrowser,項目名稱:plugin.video.emby,代碼行數:22,代碼來源:isoparser.py

示例3: _convert_1d

# 需要導入模塊: from datetime import datetime [as 別名]
# 或者: from datetime.datetime import time [as 別名]
def _convert_1d(values, units, axis):
        if not hasattr(axis, 'freq'):
            raise TypeError('Axis must have `freq` set to convert to Periods')
        valid_types = (compat.string_types, datetime,
                       Period, pydt.date, pydt.time, np.datetime64)
        if (isinstance(values, valid_types) or is_integer(values) or
                is_float(values)):
            return get_datevalue(values, axis.freq)
        elif isinstance(values, PeriodIndex):
            return values.asfreq(axis.freq)._ndarray_values
        elif isinstance(values, Index):
            return values.map(lambda x: get_datevalue(x, axis.freq))
        elif lib.infer_dtype(values, skipna=False) == 'period':
            # https://github.com/pandas-dev/pandas/issues/24304
            # convert ndarray[period] -> PeriodIndex
            return PeriodIndex(values, freq=axis.freq)._ndarray_values
        elif isinstance(values, (list, tuple, np.ndarray, Index)):
            return [get_datevalue(x, axis.freq) for x in values]
        return values 
開發者ID:Frank-qlu,項目名稱:recruit,代碼行數:21,代碼來源:_converter.py

示例4: test_datetime_time

# 需要導入模塊: from datetime import datetime [as 別名]
# 或者: from datetime.datetime import time [as 別名]
def test_datetime_time(self):
        # test support for datetime.time
        df = DataFrame([time(9, 0, 0), time(9, 1, 30)], columns=["a"])
        df.to_sql('test_time', self.conn, index=False)
        res = read_sql_table('test_time', self.conn)
        tm.assert_frame_equal(res, df)

        # GH8341
        # first, use the fallback to have the sqlite adapter put in place
        sqlite_conn = TestSQLiteFallback.connect()
        sql.to_sql(df, "test_time2", sqlite_conn, index=False)
        res = sql.read_sql_query("SELECT * FROM test_time2", sqlite_conn)
        ref = df.applymap(lambda _: _.strftime("%H:%M:%S.%f"))
        tm.assert_frame_equal(ref, res)  # check if adapter is in place
        # then test if sqlalchemy is unaffected by the sqlite adapter
        sql.to_sql(df, "test_time3", self.conn, index=False)
        if self.flavor == 'sqlite':
            res = sql.read_sql_query("SELECT * FROM test_time3", self.conn)
            ref = df.applymap(lambda _: _.strftime("%H:%M:%S.%f"))
            tm.assert_frame_equal(ref, res)
        res = sql.read_sql_table("test_time3", self.conn)
        tm.assert_frame_equal(df, res) 
開發者ID:Frank-qlu,項目名稱:recruit,代碼行數:24,代碼來源:test_sql.py

示例5: _maybe_normalize_endpoints

# 需要導入模塊: from datetime import datetime [as 別名]
# 或者: from datetime.datetime import time [as 別名]
def _maybe_normalize_endpoints(start, end, normalize):
    _normalized = True

    if start is not None:
        if normalize:
            start = normalize_date(start)
            _normalized = True
        else:
            _normalized = _normalized and start.time() == _midnight

    if end is not None:
        if normalize:
            end = normalize_date(end)
            _normalized = True
        else:
            _normalized = _normalized and end.time() == _midnight

    return start, end, _normalized 
開發者ID:Frank-qlu,項目名稱:recruit,代碼行數:20,代碼來源:datetimes.py

示例6: snap

# 需要導入模塊: from datetime import datetime [as 別名]
# 或者: from datetime.datetime import time [as 別名]
def snap(self, freq='S'):
        """
        Snap time stamps to nearest occurring frequency
        """
        # Superdumb, punting on any optimizing
        freq = to_offset(freq)

        snapped = np.empty(len(self), dtype=_NS_DTYPE)

        for i, v in enumerate(self):
            s = v
            if not freq.onOffset(s):
                t0 = freq.rollback(s)
                t1 = freq.rollforward(s)
                if abs(s - t0) < abs(t1 - s):
                    s = t0
                else:
                    s = t1
            snapped[i] = s

        # we know it conforms; skip check
        return DatetimeIndex._simple_new(snapped, freq=freq)
        # TODO: what about self.name?  tz? if so, use shallow_copy? 
開發者ID:Frank-qlu,項目名稱:recruit,代碼行數:25,代碼來源:datetimes.py

示例7: _DATETIME_to_python

# 需要導入模塊: from datetime import datetime [as 別名]
# 或者: from datetime.datetime import time [as 別名]
def _DATETIME_to_python(self, value, dsc=None):
        """Connector/Python always returns naive datetime.datetime

        Connector/Python always returns naive timestamps since MySQL has
        no time zone support. Since Django needs non-naive, we need to add
        the UTC time zone.

        Returns datetime.datetime()
        """
        if not value:
            return None
        dt = MySQLConverter._DATETIME_to_python(self, value)
        if dt is None:
            return None
        if settings.USE_TZ and timezone.is_naive(dt):
            dt = dt.replace(tzinfo=timezone.utc)
        return dt 
開發者ID:LuciferJack,項目名稱:python-mysql-pool,代碼行數:19,代碼來源:base.py

示例8: _convert_1d

# 需要導入模塊: from datetime import datetime [as 別名]
# 或者: from datetime.datetime import time [as 別名]
def _convert_1d(values, units, axis):
        if not hasattr(axis, 'freq'):
            raise TypeError('Axis must have `freq` set to convert to Periods')
        valid_types = (compat.string_types, datetime,
                       Period, pydt.date, pydt.time, np.datetime64)
        if (isinstance(values, valid_types) or is_integer(values) or
                is_float(values)):
            return get_datevalue(values, axis.freq)
        if isinstance(values, PeriodIndex):
            return values.asfreq(axis.freq)._ndarray_values
        if isinstance(values, Index):
            return values.map(lambda x: get_datevalue(x, axis.freq))
        if is_period_arraylike(values):
            return PeriodIndex(values, freq=axis.freq)._ndarray_values
        if isinstance(values, (list, tuple, np.ndarray, Index)):
            return [get_datevalue(x, axis.freq) for x in values]
        return values 
開發者ID:birforce,項目名稱:vnpy_crypto,代碼行數:19,代碼來源:_converter.py

示例9: snap

# 需要導入模塊: from datetime import datetime [as 別名]
# 或者: from datetime.datetime import time [as 別名]
def snap(self, freq='S'):
        """
        Snap time stamps to nearest occurring frequency

        """
        # Superdumb, punting on any optimizing
        freq = to_offset(freq)

        snapped = np.empty(len(self), dtype=_NS_DTYPE)

        for i, v in enumerate(self):
            s = v
            if not freq.onOffset(s):
                t0 = freq.rollback(s)
                t1 = freq.rollforward(s)
                if abs(s - t0) < abs(t1 - s):
                    s = t0
                else:
                    s = t1
            snapped[i] = s

        # we know it conforms; skip check
        return DatetimeIndex(snapped, freq=freq, verify_integrity=False) 
開發者ID:birforce,項目名稱:vnpy_crypto,代碼行數:25,代碼來源:datetimes.py

示例10: convert_datetime_to_epoch

# 需要導入模塊: from datetime import datetime [as 別名]
# 或者: from datetime.datetime import time [as 別名]
def convert_datetime_to_epoch(dt: datetime) -> float:
    """Converts datetime to epoch time in seconds.

    If Python > 3.3, you may use timestamp() method.
    """
    if dt.tzinfo is not None:
        dt0 = dt.astimezone(pytz.UTC).replace(tzinfo=None)
    else:
        dt0 = dt
    return (dt0 - ZERO_EPOCH).total_seconds() 
開發者ID:snowflakedb,項目名稱:snowflake-connector-python,代碼行數:12,代碼來源:converter.py

示例11: _TIME_to_python

# 需要導入模塊: from datetime import datetime [as 別名]
# 或者: from datetime.datetime import time [as 別名]
def _TIME_to_python(self, ctx):
        """TIME to formatted string, SnowflakeDateTime, or datetime.time with no timezone attached."""
        scale = ctx['scale']

        conv0 = lambda value: datetime.utcfromtimestamp(float(value)).time()

        def conv(value: str) -> dt_t:
            microseconds = float(value[0:-scale + 6])
            return datetime.utcfromtimestamp(microseconds).time()

        return conv if scale > 6 else conv0 
開發者ID:snowflakedb,項目名稱:snowflake-connector-python,代碼行數:13,代碼來源:converter.py

示例12: _derive_offset_timestamp

# 需要導入模塊: from datetime import datetime [as 別名]
# 或者: from datetime.datetime import time [as 別名]
def _derive_offset_timestamp(self, value, is_utc: bool = False):
        """Derives TZ offset and timestamp from the datetime objects."""
        tzinfo = value.tzinfo
        if tzinfo is None:
            # If no tzinfo is attached, use local timezone.
            tzinfo = self._get_session_tz() if not is_utc else pytz.UTC
            t = pytz.utc.localize(value, is_dst=False).astimezone(tzinfo)
        else:
            # if tzinfo is attached, just covert to epoch time
            # as the server expects it in UTC anyway
            t = value
        offset = tzinfo.utcoffset(
            t.replace(tzinfo=None)).total_seconds() / 60 + 1440
        return offset, t 
開發者ID:snowflakedb,項目名稱:snowflake-connector-python,代碼行數:16,代碼來源:converter.py

示例13: _struct_time_to_snowflake_bindings

# 需要導入模塊: from datetime import datetime [as 別名]
# 或者: from datetime.datetime import time [as 別名]
def _struct_time_to_snowflake_bindings(self, snowflake_type, value):
        return self._datetime_to_snowflake_bindings(
            snowflake_type,
            datetime.fromtimestamp(time.mktime(value))) 
開發者ID:snowflakedb,項目名稱:snowflake-connector-python,代碼行數:6,代碼來源:converter.py

示例14: __init__

# 需要導入模塊: from datetime import datetime [as 別名]
# 或者: from datetime.datetime import time [as 別名]
def __init__(self, sep=None):
        """
        :param sep:
            A single character that separates date and time portions. If
            ``None``, the parser will accept any single character.
            For strict ISO-8601 adherence, pass ``'T'``.
        """
        if sep is not None:
            if (len(sep) != 1 or ord(sep) >= 128 or sep in '0123456789'):
                raise ValueError('Separator must be a single, non-numeric ' +
                                 'ASCII character')

            sep = sep.encode('ascii')

        self._sep = sep 
開發者ID:MediaBrowser,項目名稱:plugin.video.emby,代碼行數:17,代碼來源:isoparser.py

示例15: parse_isotime

# 需要導入模塊: from datetime import datetime [as 別名]
# 或者: from datetime.datetime import time [as 別名]
def parse_isotime(self, timestr):
        """
        Parse the time portion of an ISO string.

        :param timestr:
            The time portion of an ISO string, without a separator

        :return:
            Returns a :class:`datetime.time` object
        """
        return time(*self._parse_isotime(timestr)) 
開發者ID:MediaBrowser,項目名稱:plugin.video.emby,代碼行數:13,代碼來源:isoparser.py


注:本文中的datetime.datetime.time方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。