本文整理汇总了Python中isodate.parse_duration方法的典型用法代码示例。如果您正苦于以下问题:Python isodate.parse_duration方法的具体用法?Python isodate.parse_duration怎么用?Python isodate.parse_duration使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类isodate
的用法示例。
在下文中一共展示了isodate.parse_duration方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _pythonize_objects
# 需要导入模块: import isodate [as 别名]
# 或者: from isodate import parse_duration [as 别名]
def _pythonize_objects(scrapings: List[Dict], python_objects: Union[bool,
List, Tuple]) -> List[Dict]:
if python_objects is False:
# this really should not be happening
return scrapings
# this should work, mypy gives error, this isn't bulletproof code
if python_objects is True or datetime.timedelta in python_objects: # type: ignore
# convert ISO 8601 date times into timedelta
scrapings = _convert_properties_scrape(scrapings, DURATION_PROPERTIES,
isodate.parse_duration)
if python_objects is True or _have_matching_items((datetime.date, datetime.datetime), python_objects):
# convert ISO 8601 date times into datetimes.datetime objects
scrapings = _convert_properties_scrape(scrapings, DATETIME_PROPERTIES,
_parse_determine_date_datetime)
return scrapings
示例2: deserialize_duration
# 需要导入模块: import isodate [as 别名]
# 或者: from isodate import parse_duration [as 别名]
def deserialize_duration(attr):
"""Deserialize ISO-8601 formatted string into TimeDelta object.
:param str attr: response string to be deserialized.
:rtype: TimeDelta
:raises: DeserializationError if string format invalid.
"""
if isinstance(attr, ET.Element):
attr = attr.text
try:
duration = isodate.parse_duration(attr)
except(ValueError, OverflowError, AttributeError) as err:
msg = "Cannot deserialize duration object."
raise_with_traceback(DeserializationError, msg, err)
else:
return duration
示例3: test_attr_duration
# 需要导入模块: import isodate [as 别名]
# 或者: from isodate import parse_duration [as 别名]
def test_attr_duration(self):
"""
Test serializing a duration
"""
test_obj = self.TestObj()
test_obj.attr_f = timedelta(days=1)
message = self.s._serialize(test_obj)
self.assertEqual("P1D", message["AttrF"])
test_obj = self.TestObj()
test_obj.attr_f = isodate.parse_duration("P3Y6M4DT12H30M5S")
message = self.s.body({
"attr_f": isodate.parse_duration("P3Y6M4DT12H30M5S")},
'TestObj')
self.assertEqual("P3Y6M4DT12H30M5S", message["AttrF"])
示例4: compute_time_compare
# 需要导入模块: import isodate [as 别名]
# 或者: from isodate import parse_duration [as 别名]
def compute_time_compare(granularity, periods):
if not granularity:
return None
# convert old db_engine_spec granularity to ISO duration
if granularity in db_engine_specs_map:
granularity = db_engine_specs_map[granularity]
try:
obj = isodate.parse_duration(granularity) * periods
except isodate.isoerror.ISO8601Error:
# if parse_human_timedelta can parse it, return it directly
delta = "{0} {1}{2}".format(periods, granularity, "s" if periods > 1 else "")
obj = parse_human_timedelta(delta)
if obj:
return delta
raise Exception("Unable to parse: {0}".format(granularity))
if isinstance(obj, isodate.duration.Duration):
return isodate_duration_to_string(obj)
elif isinstance(obj, datetime.timedelta):
return timedelta_to_string(obj)
开发者ID:apache,项目名称:incubator-superset,代码行数:23,代码来源:3dda56f1c4c6_migrate_num_period_compare_and_period_.py
示例5: _parse_album_track
# 需要导入模块: import isodate [as 别名]
# 或者: from isodate import parse_duration [as 别名]
def _parse_album_track(self, track_html):
"""Returns a TrackInfo derived from the html describing a track in a
bandcamp album page.
"""
track_num = track_html['rel'].split('=')[1]
track_num = int(track_num)
title_html = track_html.find(attrs={'class': 'title-col'})
title = title_html.find(attrs={'itemprop': 'name'}).text.strip()
artist = None
if self.config['split_artist_title']:
artist, title = self._split_artist_title(title)
track_url = title_html.find(attrs={'itemprop': 'url'})
if track_url is None:
raise BandcampException('No track url (id) for track {0} - {1}'.format(track_num, title))
track_id = track_url['href']
try:
duration = title_html.find('meta', attrs={'itemprop': 'duration'})['content']
duration = duration.replace('P', 'PT')
track_length = isodate.parse_duration(duration).total_seconds()
except TypeError:
track_length = None
return TrackInfo(title, track_id, index=track_num, length=track_length, artist=artist)
示例6: parse_duration
# 需要导入模块: import isodate [as 别名]
# 或者: from isodate import parse_duration [as 别名]
def parse_duration(duration, timestamp=None):
"""
Interprets a ISO8601 duration value relative to a given timestamp.
:param duration: The duration, as a string.
:type: string
:param timestamp: The unix timestamp we should apply the duration to.
Optional, default to the current time.
:type: string
:return: The new timestamp, after the duration is applied.
:rtype: int
"""
assert isinstance(duration, compat.str_type)
assert timestamp is None or isinstance(timestamp, int)
timedelta = duration_parser(duration)
if timestamp is None:
data = datetime.utcnow() + timedelta
else:
data = datetime.utcfromtimestamp(timestamp) + timedelta
return calendar.timegm(data.utctimetuple())
示例7: execute_query
# 需要导入模块: import isodate [as 别名]
# 或者: from isodate import parse_duration [as 别名]
def execute_query(cmd, client, application, analytics_query, start_time=None, end_time=None, offset='1h', resource_group_name=None):
"""Executes a query against the provided Application Insights application."""
from .vendored_sdks.applicationinsights.models import QueryBody
targets = get_query_targets(cmd.cli_ctx, application, resource_group_name)
if not isinstance(offset, datetime.timedelta):
offset = isodate.parse_duration(offset)
try:
return client.query.execute(targets[0], QueryBody(query=analytics_query, timespan=get_timespan(cmd.cli_ctx, start_time, end_time, offset), applications=targets[1:]))
except ErrorResponseException as ex:
if "PathNotFoundError" in ex.message:
raise ValueError("The Application Insight is not found. Please check the app id again.")
raise ex
示例8: to_internal_value
# 需要导入模块: import isodate [as 别名]
# 或者: from isodate import parse_duration [as 别名]
def to_internal_value(self, data):
if data:
value = parse_duration(data)
return (
value.days * 24 * 3600 * 1000000 +
value.seconds * 1000 +
value.microseconds / 1000
)
else:
return 0
示例9: create_pleblist_song_info
# 需要导入模块: import isodate [as 别名]
# 或者: from isodate import parse_duration [as 别名]
def create_pleblist_song_info(youtube_id):
import isodate
from apiclient.errors import HttpError
if PleblistManager.youtube is None:
log.warning("youtube was not initialized")
return False
try:
video_response = (
PleblistManager.youtube.videos().list(id=str(youtube_id), part="snippet,contentDetails").execute()
)
except HttpError as e:
log.exception("Youtube HTTPError")
log.info(e.content)
log.info(e.resp)
log.info(e.uri)
return False
except:
log.exception("uncaught exception in videos().list()")
return False
if not video_response.get("items", []):
log.warning(f"Got no valid responses for {youtube_id}")
return False
video = video_response["items"][0]
title = video["snippet"]["title"]
duration = int(isodate.parse_duration(video["contentDetails"]["duration"]).total_seconds())
default_thumbnail = video["snippet"]["thumbnails"]["default"]["url"]
return PleblistSongInfo(youtube_id, title, duration, default_thumbnail)
示例10: duration
# 需要导入模块: import isodate [as 别名]
# 或者: from isodate import parse_duration [as 别名]
def duration(duration):
return parse_duration(duration)
示例11: cast_duration
# 需要导入模块: import isodate [as 别名]
# 或者: from isodate import parse_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
示例12: iso8601_as_timedelta
# 需要导入模块: import isodate [as 别名]
# 或者: from isodate import parse_duration [as 别名]
def iso8601_as_timedelta(iso):
"""Convert an ISO 8601 string to a timdelta"""
# TODO: Decide what to do with months or years.
try:
duration = isodate.parse_duration(iso)
except isodate.isoerror.ISO8601Error:
raise ValueError("Invalid ISO duration")
if type(duration) != datetime.timedelta:
raise ValueError("Cannot support months or years")
return duration
示例13: youtime
# 需要导入模块: import isodate [as 别名]
# 或者: from isodate import parse_duration [as 别名]
def youtime(text: str, reply) -> str:
"""<query> - Gets the total run time of the first YouTube search result for <query>."""
parts = ["statistics", "contentDetails", "snippet"]
try:
video_id = get_video_id(text)
request = get_video(video_id, parts)
raise_api_errors(request)
except NoResultsError as e:
return e.message
except APIError as e:
reply(e.message)
raise
json = request.json()
data = json["items"]
item = data[0]
snippet = item["snippet"]
content_details = item["contentDetails"]
statistics = item["statistics"]
duration = content_details.get("duration")
if not duration:
return "Missing duration in API response"
length = isodate.parse_duration(duration)
l_sec = int(length.total_seconds())
views = int(statistics["viewCount"])
total = int(l_sec * views)
length_text = timeformat.format_time(l_sec, simple=True)
total_text = timeformat.format_time(total, accuracy=8)
return (
"The video \x02{}\x02 has a length of {} and has been viewed {:,} times for "
"a total run time of {}!".format(
snippet["title"], length_text, views, total_text
)
)
示例14: xml_text_to_value
# 需要导入模块: import isodate [as 别名]
# 或者: from isodate import parse_duration [as 别名]
def xml_text_to_value(value, value_type):
# We can't handle bytes in this function because str == bytes on Python2
from .ewsdatetime import EWSDateTime
return {
bool: lambda v: True if v == 'true' else False if v == 'false' else None,
int: int,
Decimal: Decimal,
datetime.timedelta: isodate.parse_duration,
EWSDateTime: EWSDateTime.from_string,
str: lambda v: v
}[value_type](value)
示例15: serialize_duration
# 需要导入模块: import isodate [as 别名]
# 或者: from isodate import parse_duration [as 别名]
def serialize_duration(attr, **kwargs):
"""Serialize TimeDelta object into ISO-8601 formatted string.
:param TimeDelta attr: Object to be serialized.
:rtype: str
"""
if isinstance(attr, str):
attr = isodate.parse_duration(attr)
return isodate.duration_isoformat(attr)