Python isodate.duration_isoformat() Examples
The following are 13
code examples of isodate.duration_isoformat().
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 |
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: extended_json.py From datapackage-pipelines with MIT License | 6 votes |
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 #3
Source File: messages.py From motorway with Apache License 2.0 | 6 votes |
def fail(self, error_message="", capture_exception=True): """ Send a message to the controller that this message failed to process """ self.controller_queue.send_json({ 'ramp_unique_id': self.ramp_unique_id, 'ack_value': -1, 'content': { 'process_name': self.process_name, 'msg_type': 'fail', 'duration': duration_isoformat(datetime.datetime.now() - self.init_time), 'message_content': self.content }, 'producer_uuid': self.producer_uuid, 'destination_uuid': self.producer_uuid, 'error_message': error_message if not capture_exception else traceback.format_exc(), })
Example #4
Source File: serialize.py From k8s-snapshots with BSD 2-Clause "Simplified" License | 6 votes |
def process( obj, fallback_processor: Optional[ Callable[..., Serializable] ]=_DEFAULT_FALLBACK_PROCESSOR, ) -> Serializable: if isinstance(obj, timedelta): return isodate.duration_isoformat(obj) if isinstance(obj, pendulum.Pendulum): return obj.isoformat() if fallback_processor is not None: return fallback_processor(obj) raise TypeError( f'Cannot process object of type {type(obj)}, no fallback_processor ' f'provided' )
Example #5
Source File: api.py From linkedevents with MIT License | 5 votes |
def to_representation(self, obj): if obj: d = Duration(milliseconds=obj) return duration_isoformat(d) else: return None
Example #6
Source File: iso8601.py From pscheduler with Apache License 2.0 | 5 votes |
def timedelta_as_iso8601(timedelta): return isodate.duration_isoformat(timedelta)
Example #7
Source File: serialization.py From msrest-for-python with MIT License | 5 votes |
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)
Example #8
Source File: utils.py From motorway with Apache License 2.0 | 5 votes |
def default(self, o): if type(o) == datetime.timedelta: return duration_isoformat(o) elif type(o) == datetime.datetime: return datetime_isoformat(o) elif isinstance(o, decimal.Decimal): return float(o) return super(DateTimeAwareJsonEncoder, self).default(o)
Example #9
Source File: messages.py From motorway with Apache License 2.0 | 5 votes |
def send_control_message(self, controller_queue, time_consumed=None, process_name=None, destination_endpoint=None, destination_uuid=None, sender=None): """ Control messages are notifications that a new message have been created, so the controller can keep track of this particular message and let the ramp know once the entire tree of messages has been completed. This is called implicitly on yield Message(_id, 'message') :param process_name: UUID of the process processing this message (as string) """ content = { 'process_name': process_name, 'msg_type': 'new_msg', } if not self.producer_uuid: raise Exception("Cannot send control message without producer UUID") if time_consumed: # Ramps provide time consumed, since we don't know the "start time" like in a intersection # where it's clear when the message is received and later 'acked' as the last action content['duration'] = duration_isoformat(time_consumed) content['sender'] = sender controller_queue.send_json({ 'ramp_unique_id': self.ramp_unique_id, 'ack_value': self.ack_value, 'content': content, 'producer_uuid': self.producer_uuid, 'destination_endpoint': destination_endpoint, 'destination_uuid': destination_uuid })
Example #10
Source File: messages.py From motorway with Apache License 2.0 | 5 votes |
def ack(self, time_consumed=None): """ Send a message to the controller that this message was properly processed """ self.controller_queue.send_json({ 'ramp_unique_id': self.ramp_unique_id, 'ack_value': self.ack_value, 'content': { 'process_name': self.process_name, 'msg_type': 'ack', 'duration': duration_isoformat(time_consumed or (datetime.datetime.now() - self.init_time)) }, 'producer_uuid': self.producer_uuid, 'destination_uuid': self.producer_uuid })
Example #11
Source File: rule.py From k8s-snapshots with BSD 2-Clause "Simplified" License | 5 votes |
def serialize_deltas(deltas: Iterable[timedelta]) -> str: delta_strs = [ isodate.duration_isoformat(delta) for delta in deltas ] return ' '.join(delta_strs)
Example #12
Source File: utils.py From hawthorne with GNU Lesser General Public License v3.0 | 5 votes |
def isoduration(v): return isodate.duration_isoformat(v)
Example #13
Source File: config.py From modmail with GNU Affero General Public License v3.0 | 4 votes |
def set(self, key: str, item: typing.Any, convert=True) -> None: if not convert: return self.__setitem__(key, item) if key in self.colors: try: hex_ = str(item) if hex_.startswith("#"): hex_ = hex_[1:] if len(hex_) == 3: hex_ = "".join(s for s in hex_ for _ in range(2)) if len(hex_) != 6: raise InvalidConfigError("Invalid color name or hex.") try: int(hex_, 16) except ValueError: raise InvalidConfigError("Invalid color name or hex.") except InvalidConfigError: name = str(item).lower() name = re.sub(r"[\-+|. ]+", " ", name) hex_ = ALL_COLORS.get(name) if hex_ is None: name = re.sub(r"[\-+|. ]+", "", name) hex_ = ALL_COLORS.get(name) if hex_ is None: raise return self.__setitem__(key, "#" + hex_) if key in self.time_deltas: try: isodate.parse_duration(item) except isodate.ISO8601Error: try: converter = UserFriendlyTimeSync() time = converter.convert(None, item) if time.arg: raise ValueError except BadArgument as exc: raise InvalidConfigError(*exc.args) except Exception as e: logger.debug(e) raise InvalidConfigError( "Unrecognized time, please use ISO-8601 duration format " 'string or a simpler "human readable" time.' ) item = isodate.duration_isoformat(time.dt - converter.now) return self.__setitem__(key, item) if key in self.booleans: try: return self.__setitem__(key, strtobool(item)) except ValueError: raise InvalidConfigError("Must be a yes/no value.") # elif key in self.special_types: # if key == "status": return self.__setitem__(key, item)