本文整理汇总了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
示例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
示例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
示例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)
示例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
示例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?
示例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
示例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
示例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)
示例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()
示例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
示例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
示例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)))
示例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
示例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))