本文整理汇总了Python中isodate.Duration方法的典型用法代码示例。如果您正苦于以下问题:Python isodate.Duration方法的具体用法?Python isodate.Duration怎么用?Python isodate.Duration使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类isodate
的用法示例。
在下文中一共展示了isodate.Duration方法的11个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: default
# 需要导入模块: import isodate [as 别名]
# 或者: from isodate import Duration [as 别名]
def default(self, obj):
if isinstance(obj, decimal.Decimal):
return {'type{decimal}': str(obj)}
elif isinstance(obj, datetime.time):
return {'type{time}': obj.strftime(TIME_FORMAT)}
elif isinstance(obj, datetime.datetime):
return {'type{datetime}':
(obj.strftime(DATETIME_FORMAT),
obj.utcoffset().seconds if obj.utcoffset() is not None else None,
obj.tzname())}
elif isinstance(obj, datetime.date):
return {'type{date}': obj.strftime(DATE_FORMAT)}
elif isinstance(obj, (isodate.Duration, datetime.timedelta)):
return {'type{duration}': isodate.duration_isoformat(obj)}
elif isinstance(obj, set):
return {'type{set}': list(obj)}
return super().default(obj)
示例2: __init__
# 需要导入模块: import isodate [as 别名]
# 或者: from isodate import Duration [as 别名]
def __init__(self, node, root=None, parent=None, *args, **kwargs):
super(Period, self).__init__(node, root, parent, *args, **kwargs)
self.i = kwargs.get(u"i", 0)
self.id = self.attr(u"id")
self.bitstreamSwitching = self.attr(u"bitstreamSwitching", parser=MPDParsers.bool_str)
self.duration = self.attr(u"duration", default=Duration(), parser=MPDParsers.duration)
self.start = self.attr(u"start", default=Duration(), parser=MPDParsers.duration)
if self.start is None and self.i == 0 and self.root.type == "static":
self.start = 0
# TODO: Early Access Periods
self.baseURLs = self.children(BaseURL)
self.segmentBase = self.only_child(SegmentBase)
self.adaptationSets = self.children(AdaptationSet, minimum=1)
self.segmentList = self.only_child(SegmentList)
self.segmentTemplate = self.only_child(SegmentTemplate)
self.sssetIdentifier = self.only_child(AssetIdentifier)
self.eventStream = self.children(EventStream)
self.subset = self.children(Subset)
示例3: default
# 需要导入模块: import isodate [as 别名]
# 或者: from isodate import Duration [as 别名]
def default(self, obj):
if isinstance(obj, decimal.Decimal):
return {'type{decimal}': str(obj)}
elif isinstance(obj, datetime.time):
return {'type{time}': obj.strftime(TIME_FORMAT)}
elif isinstance(obj, datetime.datetime):
return {'type{datetime}': obj.strftime(DATETIME_FORMAT)}
elif isinstance(obj, datetime.date):
return {'type{date}': obj.strftime(DATE_FORMAT)}
elif isinstance(obj, (isodate.Duration, datetime.timedelta)):
return {'type{duration}': isodate.duration_isoformat(obj)}
elif isinstance(obj, set):
return {'type{set}': list(obj)}
elif isinstance(obj, LazyDict):
return obj.inner
return super().default(obj)
示例4: to_representation
# 需要导入模块: import isodate [as 别名]
# 或者: from isodate import Duration [as 别名]
def to_representation(self, obj):
if obj:
d = Duration(milliseconds=obj)
return duration_isoformat(d)
else:
return None
示例5: cast_duration
# 需要导入模块: import isodate [as 别名]
# 或者: from isodate import Duration [as 别名]
def cast_duration(format, value, **options):
if not isinstance(value, (isodate.Duration, datetime.timedelta)):
if not isinstance(value, six.string_types):
return ERROR
try:
value = isodate.parse_duration(value)
except Exception:
return ERROR
return value
示例6: get_thread_cooldown
# 需要导入模块: import isodate [as 别名]
# 或者: from isodate import Duration [as 别名]
def get_thread_cooldown(self, author: discord.Member):
thread_cooldown = self.config.get("thread_cooldown")
now = datetime.utcnow()
if thread_cooldown == isodate.Duration():
return
last_log = await self.api.get_latest_user_logs(author.id)
if last_log is None:
logger.debug("Last thread wasn't found, %s.", author.name)
return
last_log_closed_at = last_log.get("closed_at")
if not last_log_closed_at:
logger.debug("Last thread was not closed, %s.", author.name)
return
try:
cooldown = datetime.fromisoformat(last_log_closed_at) + thread_cooldown
except ValueError:
logger.warning("Error with 'thread_cooldown'.", exc_info=True)
cooldown = datetime.fromisoformat(last_log_closed_at) + self.config.remove(
"thread_cooldown"
)
if cooldown > now:
# User messaged before thread cooldown ended
delta = human_timedelta(cooldown)
logger.debug("Blocked due to thread cooldown, user %s.", author.name)
return delta
return
示例7: _restart_close_timer
# 需要导入模块: import isodate [as 别名]
# 或者: from isodate import Duration [as 别名]
def _restart_close_timer(self):
"""
This will create or restart a timer to automatically close this
thread.
"""
timeout = self.bot.config.get("thread_auto_close")
# Exit if timeout was not set
if timeout == isodate.Duration():
return
# Set timeout seconds
seconds = timeout.total_seconds()
# seconds = 20 # Uncomment to debug with just 20 seconds
reset_time = datetime.utcnow() + timedelta(seconds=seconds)
human_time = human_timedelta(dt=reset_time)
if self.bot.config.get("thread_auto_close_silently"):
return await self.close(
closer=self.bot.user, silent=True, after=int(seconds), auto_close=True
)
# Grab message
close_message = self.bot.formatter.format(
self.bot.config["thread_auto_close_response"], timeout=human_time
)
time_marker_regex = "%t"
if len(re.findall(time_marker_regex, close_message)) == 1:
close_message = re.sub(time_marker_regex, str(human_time), close_message)
elif len(re.findall(time_marker_regex, close_message)) > 1:
logger.warning(
"The thread_auto_close_response should only contain one '%s' to specify time.",
time_marker_regex,
)
await self.close(
closer=self.bot.user, after=int(seconds), message=close_message, auto_close=True
)
示例8: __init__
# 需要导入模块: import isodate [as 别名]
# 或者: from isodate import Duration [as 别名]
def __init__(self, classes=None):
self.deserialize_type = {
'iso-8601': Deserializer.deserialize_iso,
'rfc-1123': Deserializer.deserialize_rfc,
'unix-time': Deserializer.deserialize_unix,
'duration': Deserializer.deserialize_duration,
'date': Deserializer.deserialize_date,
'time': Deserializer.deserialize_time,
'decimal': Deserializer.deserialize_decimal,
'long': Deserializer.deserialize_long,
'bytearray': Deserializer.deserialize_bytearray,
'base64': Deserializer.deserialize_base64,
'object': self.deserialize_object,
'[]': self.deserialize_iter,
'{}': self.deserialize_dict
}
self.deserialize_expected_types = {
'duration': (isodate.Duration, datetime.timedelta),
'iso-8601': (datetime.datetime)
}
self.dependencies = dict(classes) if classes else {}
self.key_extractors = [
rest_key_extractor,
xml_key_extractor
]
# Additional properties only works if the "rest_key_extractor" is used to
# extract the keys. Making it to work whatever the key extractor is too much
# complicated, with no real scenario for now.
# So adding a flag to disable additional properties detection. This flag should be
# used if your expect the deserialization to NOT come from a JSON REST syntax.
# Otherwise, result are unexpected
self.additional_properties_detection = True
示例9: parse_deltas
# 需要导入模块: import isodate [as 别名]
# 或者: from isodate import Duration [as 别名]
def parse_deltas(
delta_string: str
) -> List[Union[timedelta, isodate.Duration]]:
"""q§Parse the given string into a list of ``timedelta`` instances.
"""
if delta_string is None:
raise DeltasParseError(
f'Delta string is None',
)
deltas = []
for item in delta_string.split(' '):
item = item.strip()
if not item:
continue
try:
deltas.append(isodate.parse_duration(item))
except ValueError as exc:
raise DeltasParseError(
f'Could not parse duration: {item!r}',
error=exc,
item=item,
deltas=deltas,
delta_string=delta_string,
) from exc
if deltas and len(deltas) < 2:
raise DeltasParseError(
'At least two deltas are required',
deltas=deltas,
delta_string=delta_string,
)
return deltas
示例10: restore_type
# 需要导入模块: import isodate [as 别名]
# 或者: from isodate import Duration [as 别名]
def restore_type(self, dtype, sample=None):
"""Restore type from Pandas
"""
# Pandas types
if pdc.is_bool_dtype(dtype):
return 'boolean'
elif pdc.is_datetime64_any_dtype(dtype):
return 'datetime'
elif pdc.is_integer_dtype(dtype):
return 'integer'
elif pdc.is_numeric_dtype(dtype):
return 'number'
# Python types
if sample is not None:
if isinstance(sample, (list, tuple)):
return 'array'
elif isinstance(sample, datetime.date):
return 'date'
elif isinstance(sample, isodate.Duration):
return 'duration'
elif isinstance(sample, dict):
return 'object'
elif isinstance(sample, six.string_types):
return 'string'
elif isinstance(sample, datetime.time):
return 'time'
return 'string'
示例11: get
# 需要导入模块: import isodate [as 别名]
# 或者: from isodate import Duration [as 别名]
def get(self, key: str, convert=True) -> typing.Any:
value = self.__getitem__(key)
if not convert:
return value
if key in self.colors:
try:
return int(value.lstrip("#"), base=16)
except ValueError:
logger.error("Invalid %s provided.", key)
value = int(self.remove(key).lstrip("#"), base=16)
elif key in self.time_deltas:
if not isinstance(value, isodate.Duration):
try:
value = isodate.parse_duration(value)
except isodate.ISO8601Error:
logger.warning(
"The {account} age limit needs to be a "
'ISO-8601 duration formatted duration, not "%s".',
value,
)
value = self.remove(key)
elif key in self.booleans:
try:
value = strtobool(value)
except ValueError:
value = self.remove(key)
elif key in self.special_types:
if value is None:
return None
if key == "status":
try:
# noinspection PyArgumentList
value = discord.Status(value)
except ValueError:
logger.warning("Invalid status %s.", value)
value = self.remove(key)
elif key == "activity_type":
try:
# noinspection PyArgumentList
value = discord.ActivityType(value)
except ValueError:
logger.warning("Invalid activity %s.", value)
value = self.remove(key)
return value