def duration2str(seconds): t = Time(hour=seconds // 3600, minute=(seconds // 60) % 60, second=seconds % 60) if t.hour: return t.strftime('%H:%M:%S') else: return t.strftime('%M:%S')
def __init__(self, recorded_at: time, response_timestamp: datetime, expected_arrival_time: time, current_location: GeoPoint): self.recorded_at: time = recorded_at.replace(microsecond=0) self.response_timestamp: datetime = response_timestamp.astimezone() self.expected_arrival_time: time = expected_arrival_time.replace(microsecond=0) self.current_location: GeoPoint = current_location
def equals_time(value: time, another: Any, formats: List[str]) -> bool: """ microsecond is ignored """ if isinstance(another, time): return value.replace(microsecond=0) == another.replace(microsecond=0) elif isinstance(another, str): parsed, another_value = is_time(another, formats) return parsed and value.replace(microsecond=0) == another_value.replace(microsecond=0) else: return False
def add_call(self, date: datetime.date, time_begin: datetime.time, time_end: datetime.time, dispatch_number: Optional[int] = None, sender_city_id: Optional[int] = None, sender_phone: Optional[str] = None, sender_name: Optional[str] = None, weight: Optional[int] = None, comment: Optional[str] = None, lunch_begin: Optional[datetime.time] = None, lunch_end: Optional[datetime.time] = None, ignore_time: bool = False) -> SubElement: """ Добавление вызова курьера :param date: дата ожидания курьера :param time_begin: время начала ожидания :param time_end: время окончания ожидания :param int dispatch_number: Номер привязанного заказа :param int sender_city_id: ID города отправителя по базе СДЭК :param str sender_phone: телефон оправителя :param str sender_name: ФИО оправителя :param int weight: общий вес в граммах :param str comment: комментарий :param lunch_begin: время начала обеда :param lunch_end: время окончания обеда :param bool ignore_time: Не выполнять проверки времени приезда курьера :return: Объект вызова """ call_element = ElementTree.SubElement( self.call_courier_element, 'Call', Date=date.isoformat(), TimeBeg=time_begin.isoformat(), TimeEnd=time_end.isoformat(), ) call_element.attrib['DispatchNumber'] = dispatch_number call_element.attrib['SendCityCode'] = sender_city_id call_element.attrib['SendPhone'] = sender_phone call_element.attrib['SenderName'] = sender_name call_element.attrib['Weight'] = weight call_element.attrib['Comment'] = comment call_element.attrib['IgnoreTime'] = ignore_time if lunch_begin: call_element.attrib['LunchBeg'] = lunch_begin.isoformat() if lunch_end: call_element.attrib['LunchEnd'] = lunch_end.isoformat() self.calls.append(call_element) return call_element
def create_time_entry(self, date: datetime.date, start_time: datetime.time, end_time: datetime.time, task_id: int): response = requests.post( urllib.parse.urljoin(self.site_url, 'api/v1/time_entries'), params=dict(date=date.isoformat(), start_time=start_time.isoformat('minutes'), end_time=end_time.isoformat('minutes'), task_id=task_id), headers={'X-Auth-Token': self.api_token}) response.raise_for_status() return response.json()
def fetch_range(self, *, start: datetime.time, end: datetime.time, inclusive: bool = True, tz: str = None): if tz: start = start.replace(tzinfo=pytz.timezone(tz)) end = end.replace(tzinfo=pytz.timezone(tz)) if inclusive: filters = {"time_actual__gte": start, "time__actual__lte": end} else: filters = {"time_actual__gt": start, "time__actual__lt": end} return self.filter(**filters)
def request_flight(self, number: int, destination: str, departure_time: datetime, check_in_time: time, check_in_status: bool = 0): flight = json.dumps({ 'airline': self.airline_name, 'flight_number': self.airline_name + str(number), 'destination': destination, 'departure_time': departure_time.strftime("%d/%m/%Y, %H:%M:%S"), 'check_in_time': check_in_time.strftime("%H:%M:%S"), 'check_in_status': check_in_status, }) self.channel.basic_publish(exchange=self.exchange_name, routing_key='request', body=flight) print(f'Sent {flight}')
def __init__(self, line_name: str, license_plate: str, operator_ref: int, line_ref: int, departure_time: time, journey_ref: int, siri_records: Set[SiriRecord], doc_id: str = None, siri_ride_analytics: SiriRideAnalytics = None): """ :param doc_id: :param line_name: :param license_plate: :param operator_ref: :param line_ref: :param departure_time: :param journey_ref: The number part of trip ID. Valid value is like: 20925867. The value is reference to TripId at TripIdToDate.txt file at the GTFS :param siri_records: :param siri_ride_analytics: """ self.doc_id = doc_id self.line_name = line_name self.license_plate = license_plate self.departure_time: time = departure_time.replace(microsecond=0) self.operator_ref = int(operator_ref) self.line_ref = int(line_ref) self.journey_ref = int(journey_ref) self.siri_records: Set[SiriRecord] = siri_records self.siri_ride_analytics: SiriRideAnalytics = siri_ride_analytics
def time2str(time: dt.time, fmt: str = STD_TIME_FMT) -> str: """ :param time: dt.time object :param fmt: [optional] defaults to H:M:S :return: string """ return time.strftime(fmt)
def put_reminder(self, guild: int, member: int, key: int, channel: int = NotSpecified, timezone_: str = NotSpecified, cycles_per_day: int = NotSpecified, correction_amount: timedelta = NotSpecified, ping_interval: timedelta = NotSpecified, bed_time_utc: time = NotSpecified, show_alternating: Optional[str] = NotSpecified, ping_message: str = NotSpecified, tts_value: int = NotSpecified, tts_custom: Optional[str] = NotSpecified, response_message: str = NotSpecified, response_emotes: Optional[str] = NotSpecified, color_hex: str = NotSpecified, last_ping_utc: datetime = NotSpecified, mute_until_utc: datetime = NotSpecified, alternating_flag: bool = NotSpecified) -> Any: data = {} if channel is not NotSpecified: data['channel'] = channel if timezone_ is not NotSpecified: data['timezone'] = timezone_ if cycles_per_day is not NotSpecified: data['cycles_per_day'] = cycles_per_day if correction_amount is not NotSpecified: data['correction_amount'] = correction_amount.total_seconds() if ping_interval is not NotSpecified: data['ping_interval'] = ping_interval.total_seconds() if bed_time_utc is not NotSpecified: data['bed_time_utc'] = bed_time_utc.isoformat() if show_alternating is not NotSpecified: data['show_alternating'] = show_alternating if ping_message is not NotSpecified: data['ping_message'] = ping_message if tts_value is not NotSpecified: data['tts_value'] = tts_value if tts_custom is not NotSpecified: data['tts_custom'] = tts_custom if response_message is not NotSpecified: data['response_message'] = response_message if response_emotes is not NotSpecified: data['response_emotes'] = response_emotes if color_hex is not NotSpecified: data['color_hex'] = color_hex if last_ping_utc is not NotSpecified: data['last_ping_utc'] = last_ping_utc.isoformat() if mute_until_utc is not NotSpecified: data['mute_until_utc'] = mute_until_utc.isoformat() if alternating_flag is not NotSpecified: data['alternating_flag'] = alternating_flag return self._urlopen('PUT', 'reminder', guild=guild, member=member, key=key, data=data)
def get_time(default: dt.time = None) -> dt.time: default = str(default.replace(microsecond=0, second=default.second + 1)) if default else None time = get_input('Please enter a 24 hour time (HH:MM[:SS])', default, key=lambda x: dt.time( *(int(comp) for comp in x.split(':')))) return time
def within_time_range(self, start_time: time, end_time: time) -> "Ezlink": """Return ezlink where each journey start or/and end within the specified time range.""" if self.meta.get("within_time_range"): raise RuntimeError("Ezlink is already within_time_range=" .format(self.meta.get("within_time_range"))) start_time_str = start_time.strftime("%H:%M:%S") end_time_str = end_time.strftime("%H:%M:%S") predicate_board = (F.date_format(self.tap_in_time, "HH:mm:ss") .between(start_time_str, end_time_str)) predicate_alight = (F.date_format(self.tap_out_time, "HH:mm:ss") .between(start_time_str, end_time_str)) dataframe = (self.dataframe .filter(predicate_board | predicate_alight)) return (Ezlink(dataframe, **self.columns) .annotate("within_time_range", (start_time, end_time)))
def is_aware(value: datetime.time): """Determine if a given datetime.datetime is aware. The concept is defined in Python's docs: https://docs.python.org/library/datetime.html#datetime.tzinfo Assuming value.tzinfo is either None or a proper datetime.tzinfo, value.utcoffset() implements the appropriate logic. """ return value.utcoffset() is not None
def prepare(self, value: datetime.time) -> Optional[str]: """ Prepare for serialisation """ if value is not None: if self.ignore_timezone and value.tzinfo is not None: # Strip the timezone value = value.replace(tzinfo=None) return value
def _parse_datetime_time(time: datetime.time) -> str: time = datetime.datetime.now().replace(hour=time.hour, minute=time.minute, second=0, microsecond=0) if time < datetime.datetime.now(): time += datetime.timedelta(days=1) return time.isoformat()
def greater_or_equals_time( value: time, another: Any, formats: List[str], allow_equals: bool ) -> Tuple[bool, Optional[bool]]: """ return a tuple which first is can be compared. second is comparison result when first is true, otherwise second is none. """ if isinstance(another, time): return True, value.replace(microsecond=0) >= another.replace(microsecond=0) \ if allow_equals else value.replace(microsecond=0) > another.replace(microsecond=0) elif isinstance(another, str): parsed, another_value = is_time(another, formats) if parsed: return True, value.replace(microsecond=0) >= another_value.replace(microsecond=0) \ if allow_equals else value.replace(microsecond=0) > another_value.replace(microsecond=0) else: return False, None else: return False, None
def _unconvert_time(self, value: datetime.time): if not hasattr(value, "utcoffset") or value.utcoffset() is None: msg = f"'{value}' isn't a timezone-aware {self.__type__} instance; can't convert to GMT" raise ValueError(msg) # Transform to GMT dt = datetime.datetime( 1999, 6, 8, value.hour, value.minute, value.second, microsecond=value.microsecond, ) dt -= value.utcoffset() # type: ignore milliseconds = "{0:03d}".format((dt.microsecond + 500) // 1000) fmt = "%H%M%S.{}[0:GMT]".format(milliseconds) return dt.strftime(fmt)
def plotHans(dataDate: DataDate, near_detectors: Dict, size: int, start_time: dt.time, end_time: dt.time) -> None: fig = plt.figure(figsize=(10, 10)) fig.suptitle(dataDate.date.strftime('%y%m%d'), fontsize=20) gs = fig.add_gridspec(size, size, left=0.12, right=0.93, top=0.93, bottom=0.05, wspace=0.2, hspace=0.07) anno_opts = dict(xy=(0.5, 0.9), xycoords='axes fraction', va='center', ha='center') start_time = dt.datetime.combine(dataDate.date, start_time.time()) end_time = dt.datetime.combine(dataDate.date, end_time.time()) for n in range(size): for m in range(size): data = getDataForOneD(dataDate, near_detectors[n, m], start_time, end_time) ax = fig.add_subplot(gs[n, m]) ax.set_xlim([start_time, end_time]) ax.set_ylim([723, 745]) if m != 0: ax.set_yticks([]) if n != size - 1: ax.set_xticks([]) ax.annotate(near_detectors[n, m], **anno_opts) ax.plot(data[0], data[1], lw=1, c='green') plt.show()
def get_next_datetime(time: datetime.time): time = time.replace(second=0) now = datetime.datetime.now() if datetime.datetime.now().time() > time: date = now.replace(day=now.day + 1) else: date = now return date.replace(hour=time.hour, second=time.second, minute=time.minute, microsecond=time.microsecond)
def _time_to_millis(t: datetime.time): if t.tzinfo is not None: offset = t.utcoffset() offset = offset if offset else datetime.timedelta() offset_millis = \ (offset.days * 86400 + offset.seconds) * 10 ** 3 + offset.microseconds // 1000 else: offset_millis = TIME_EPOCH_ORDINAL minutes = t.hour * 60 + t.minute seconds = minutes * 60 + t.second return seconds * 10**3 + t.microsecond // 1000 - offset_millis
def _jsonify_time(obj: datetime.time, camel_case_keys: bool = True, arg_struct: bool = True) -> JSONType: if not arg_struct: return obj.strftime('%H:%M:%S.%f') return { MODULE_KEY: datetime.time.__module__, NAME_KEY: datetime.time.__name__, 'hour': obj.hour, 'minute': obj.minute, 'second': obj.second, 'microsecond': obj.microsecond }
def get_users_by_timing(time_: datetime.time) -> List[Dict[str, Any]]: table = dynamodb.Table(DYNAMODB_TABLE) attrs = ['id', 'active', 'message', 'name', 'last_updated'] filter = { 'active': { 'AttributeValueList': [True], 'ComparisonOperator': 'EQ' }, 'timing': { 'AttributeValueList': [time_.strftime('%H:%M')], 'ComparisonOperator': 'EQ' } } return table.scan(AttributesToGet=attrs, ScanFilter=filter)['Items']
def _format_time(_time: datetime.time = None, days: int = None) -> str: """Formats time + shift days as a string for use in __repr__.""" if _time is None: time_repr = "??:??" else: time_repr = _time.strftime("%H:%M:%S" if _time.second else "%H:%M") if days is None: days_repr = "" elif days < 0: days_repr = "{}d".format(days) else: days_repr = "+{}d".format(days) return "{}{}".format(time_repr, days_repr)
def _find_replacement_master(order: Order, time: datetime.time, order_service_id, old_master: Master): """ Tries to assign a replacement master to the `order_item` of the `order` :return: replacement `Master` or None """ # since order is canceled # the master should not rely on that money client = order.client # looking for a replacement location = client.home_address.location logger.info( f'Looking for a replacement for master {old_master.first_name} ' f'with params: service={order_service_id}, ' f'date={order.date}, time={time}, location={location}') params = FilteringParams( { 'service': order_service_id, 'date': str(order.date), 'time': time.strftime('%H:%M'), 'coordinates': f'{location.lat},{location.lon}' }, client=client, ignore_taken_slots=True) masters, slots = master_utils.search(params, FilteringFunctions.datetime) if len(masters) == 0: logger.info(f'Unable to find replacement ' f'for master {old_master.first_name}') # unable to find replacement # TODO add push notification to client and other masters return None masters = master_utils.sort_masters(masters, params.coordinates, params.distance) # we can't pick the same master masters = list(filter(lambda m: m.id != old_master.id, masters)) if len(masters) == 0: logger.info(f'After removing duplicates, no masters can be ' f'a replacement for master {old_master.first_name}') # if the old master is the only one who fits # TODO add push notification to client and other masters return None return masters[0]
def caption_time_to_caption(srt: bool, sequence_number: int, start_time: datetime.time, end_time: datetime.time, text: str, language: Optional[str]) -> str: result = "" format = "" if True == srt: # SRT format requires ',' as decimal separator rather than '.'. format = '%H:%M:%S,%f' result += "{}{}".format(sequence_number, linesep) else: format = '%H:%M:%S.%f' # Trucate microseconds to milliseconds. result += '{} --> {}{}'.format( start_time.strftime(format)[:-3], end_time.strftime(format)[:-3], linesep) if language is not None: result += '[{}] {}{}{}'.format(language, text, linesep, linesep) else: result += '{}{}{}'.format(text, linesep, linesep) return result
def _unconvert_time(self, value: datetime.time): if not hasattr(value, "utcoffset") or value.utcoffset() is None: msg = f"'{value}' must be a timezone-aware {self.__type__} instance" raise ValueError(msg) dt = datetime.datetime( 1999, 6, 8, value.hour, value.minute, value.second, microsecond=value.microsecond, tzinfo=value.tzinfo, ) return format_datetime("%H%M%S", dt)
async def send_datastream_report(self, type: str, side: str, time: datetime.time, price: Decimal, qty: int) -> None: """ Sends report about changed book to public/datastream channel. Side can be None for 'trade' reports. """ translate = {"BUY": "bid", "SELL": "ask"} assert type != "trade" or qty != 0 for (reader, writer) in self.clients.values(): message = { "type": type, "price": str(price), "quantity": qty, "time": time.timestamp(), } if side: # only for some types of reports, not for "trade" message["side"] = translate[side] await self._send_json(writer, message)
def iso_str(d: datetime.date, t: datetime.time) -> str: """ Returns the ISO formatted string of data and time together. When combining, the time must be accurate to the microsecond. Parameter d: The month-day-year Precondition: d is a date object Parameter t: The time of day Precondition: t is a time object """ assert isinstance( d, datetime.date), f'The paramater d must be a date object not {type(d)}.' assert isinstance( t, datetime.time), f'The parameter t must be a time object not {type(t)}.' return d.isoformat() + 'T' + t.isoformat()
def encode_time(self, value: datetime.time) -> str: """Extends parent function since ODL allows a time zone offset from UTC to be included, and otherwise recommends that times be suffixed with a 'Z' to clearly indicate that they are in UTC. """ t = super().encode_time(value) if value.tzinfo is None or value.tzinfo == 0: return t + "Z" else: td_str = str(value.utcoffset()) (h, m, s) = td_str.split(":") if s != "00": raise ValueError("The datetime value had a timezone offset " f"with seconds values ({value}) which is " "not allowed in ODL.") if m == "00": return t + "+" + h else: return t + f"+{h}:{m}"
def encode_time(self, value: datetime.time) -> str: """Extends parent function since ODL allows a time zone offset from UTC to be included, and otherwise recommends that times be suffixed with a 'Z' to clearly indicate that they are in UTC. """ t = super().encode_time(value) if value.tzinfo is None: return t + 'Z' else: td_str = str(value.utcoffset()) (h, m, s) = td_str.split(':') if s != '00': raise ValueError('The datetime value had a timezone offset ' f'with seconds values ({value}) which is ' 'not allowed in ODL.') if m == '00': return t + '+' + h else: return t + f'+{h}:{m}'
def set_value(self, obj, value: time): if self.default_timezone and value.tzinfo is None: value = value.replace(tzinfo=self.default_timezone) super(TimeField, self).set_value(obj, value)
def format_backend_time(time:datetime.time, format:str=time_format) -> str: return time.strftime(format)
def flatten_time(t: datetime.time): if t.second: return t.strftime('%H:%M:%S') else: return t.strftime('%H:%M')
def time_window_fmt(start:datetime.time, dur:datetime.timedelta): if start is None or dur is None: return "Anytime" finish = nptime.from_time(start) + dur fmt = "%-H%M" return "%s to %s" % (start.strftime(fmt), finish.strftime(fmt))