Python isodate.Duration() Examples

The following are 12 code examples of isodate.Duration(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module isodate , or try the search function .
Example #1
Source File: extended_json.py    From dataflows with MIT License 6 votes vote down vote up
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) 
Example #2
Source File: dash_manifest.py    From streamlink with BSD 2-Clause "Simplified" License 6 votes vote down vote up
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) 
Example #3
Source File: extended_json.py    From datapackage-pipelines with MIT License 6 votes vote down vote up
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) 
Example #4
Source File: api.py    From linkedevents with MIT License 5 votes vote down vote up
def to_representation(self, obj):
        if obj:
            d = Duration(milliseconds=obj)
            return duration_isoformat(d)
        else:
            return None 
Example #5
Source File: dash_manifest.py    From streamlink with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def __init__(self, node, root=None, parent=None, url=None, *args, **kwargs):
        # top level has no parent
        super(MPD, self).__init__(node, root=self, *args, **kwargs)
        # parser attributes
        self.url = url
        self.timelines = defaultdict(lambda: -1)
        self.timelines.update(kwargs.pop("timelines", {}))
        self.id = self.attr(u"id")
        self.profiles = self.attr(u"profiles", required=True)
        self.type = self.attr(u"type", default=u"static", parser=MPDParsers.type)
        self.minimumUpdatePeriod = self.attr(u"minimumUpdatePeriod", parser=MPDParsers.duration, default=Duration())
        self.minBufferTime = self.attr(u"minBufferTime", parser=MPDParsers.duration, required=True)
        self.timeShiftBufferDepth = self.attr(u"timeShiftBufferDepth", parser=MPDParsers.duration)
        self.availabilityStartTime = self.attr(u"availabilityStartTime", parser=MPDParsers.datetime,
                                               default=datetime.datetime.fromtimestamp(0, utc),  # earliest date
                                               required=self.type == "dynamic")
        self.publishTime = self.attr(u"publishTime", parser=MPDParsers.datetime, required=self.type == "dynamic")
        self.availabilityEndTime = self.attr(u"availabilityEndTime", parser=MPDParsers.datetime)
        self.mediaPresentationDuration = self.attr(u"mediaPresentationDuration", parser=MPDParsers.duration)
        self.suggestedPresentationDelay = self.attr(u"suggestedPresentationDelay", parser=MPDParsers.duration)

        # parse children
        location = self.children(Location)
        self.location = location[0] if location else None
        if self.location:
            self.url = self.location.text
            urlp = list(urlparse(self.url))
            if urlp[2]:
                urlp[2], _ = urlp[2].rsplit("/", 1)
            self._base_url = urlunparse(urlp)

        self.baseURLs = self.children(BaseURL)
        self.periods = self.children(Period, minimum=1)
        self.programInformation = self.children(ProgramInformation) 
Example #6
Source File: duration.py    From tableschema-py with MIT License 5 votes vote down vote up
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 
Example #7
Source File: bot.py    From modmail with GNU Affero General Public License v3.0 5 votes vote down vote up
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 
Example #8
Source File: thread.py    From modmail with GNU Affero General Public License v3.0 5 votes vote down vote up
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
        ) 
Example #9
Source File: serialization.py    From msrest-for-python with MIT License 5 votes vote down vote up
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 
Example #10
Source File: rule.py    From k8s-snapshots with BSD 2-Clause "Simplified" License 5 votes vote down vote up
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 
Example #11
Source File: mapper.py    From tableschema-pandas-py with GNU Lesser General Public License v3.0 5 votes vote down vote up
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' 
Example #12
Source File: config.py    From modmail with GNU Affero General Public License v3.0 4 votes vote down vote up
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