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 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}')
예제 #3
0
파일: utils.py 프로젝트: crashka/cm
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)
예제 #4
0
  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)))
예제 #5
0
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
    }
예제 #6
0
    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)
예제 #7
0
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']
예제 #8
0
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]
예제 #9
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
예제 #10
0
def getScheduleLine(token_: str, stopId_: str, date_: date, mintime_: time, maxtime_: time):
    """
    Using https://api-v3.mbta.com/schedules to query lines of data.
    """
    schedules = []
    url_ = SCHEDULE_MBTA_URL.format(MBTA_V3_URL)
    params_ = {'filter[stop]': stopId_, 'sort': 'arrival_time', 'filter[direction_id]': '0', 
               'filter[date]': date_.strftime('%Y-%m-%d'), 'filter[min_time]': mintime_.strftime('%H:%M'), 'filter[max_time]': maxtime_.strftime('%H:%M')}
    headers_ = {'x-api-key': token_}
    resp = requests.get(url=url_, params=params_, headers=headers_)
    raw_json = resp.json()
    for line in raw_json['data']:
        try:
            schedule_id = line['id']
            schedule = line['attributes']
            drop_off_type = schedule['drop_off_type']
            pickup_type = schedule['pickup_type']
            arrival_time = schedule['arrival_time']
            departure_time = schedule['departure_time']
            schedules.append((schedule_id, drop_off_type, pickup_type, date_, arrival_time, departure_time))
        except KeyError:
            pass
    return schedules
예제 #11
0
def time_to_str(time_to_convert: time) -> str:
    """Converts a time object to str"""

    return time_to_convert.strftime('%H:%M:%S')
예제 #12
0
 def localized_time_string(self, time: datetime.time) -> Text:
     return "{} {}".format(
         time.strftime("%-I%p"),
         self.game_time_zone.localize(datetime.datetime.now()).tzname())
예제 #13
0
파일: tools.py 프로젝트: deti/boss
def format_backend_time(time:datetime.time, format:str=time_format) -> str:
    return time.strftime(format)
예제 #14
0
 def get_time_str(self, atime: time):
     return atime.strftime(self.time_str_format)
def time_to_str(value: datetime.time) -> str:
    return value.strftime(TIME_STR_FORMAT)
def make_booking_string(start_datetime: datetime.datetime,
                        end_time: datetime.time) -> str:
    start_time_and_date_string = start_datetime.strftime(
        '%-m/%-d from %-I:%M%p')
    end_time_string = end_time.strftime('%-I:%M%p')
    return f'{start_time_and_date_string} to {end_time_string}'
예제 #17
0
 def progress(self, new_progress: time):
     """Sets the progress to a different time"""
     if type(new_progress) is time:
         self._progress = new_progress.strftime("%M")
     else:
         raise ValueError('Argument is not of type datetime')
예제 #18
0
 def hour_to_string(hour: time) -> str:
     return hour.strftime('%-H:%M')
예제 #19
0
def format_time(time_obj: time) -> str:
    """ Formats a time object to a string HH:MM, for use with section serializer """
    return '' if time_obj is None else time_obj.strftime('%H:%M')
예제 #20
0
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))
예제 #21
0
def datetimeToString(dt_time: dt.time) -> str:
    if not dt_time:
        return None
    return str(dt_time.strftime('%H:%M:%S'))
예제 #22
0
def format_time(time: dt.time) -> str:
    return time.strftime('%H:%M:%S.%f')[:-3]
예제 #23
0
 def _time_to_snowflake(self, value: dt_t) -> str:
     if value.microsecond:
         return value.strftime("%H:%M:%S.%%06d") % value.microsecond
     return value.strftime("%H:%M:%S")
예제 #24
0
 def set_subscription_time(self, user_id: int, t: time) -> None:
     self.redis.hset(str(user_id), "subscription_time", t.strftime("%H:%M"))
예제 #25
0
 def localized_time_string(self, time: datetime.time) -> str:
     return "{} {}".format(
         _normalize_am_pm_annotation(time.strftime("%-I%p")),
         self.game_time_zone.localize(datetime.datetime.now()).tzname())
예제 #26
0
def _mk_time_format(time: dt.time) -> str:
    minutes = time.strftime("%M")
    minutes = "00" if minutes == "0" else minutes
    return f"{time.strftime('%H')}:{minutes}"
예제 #27
0
 def _format_time(time_to_format: time_t) -> str:
     return time_to_format.strftime("%H:%M")
예제 #28
0
 def str_time(cls, dt: datetime.time) -> str:
     """Return the time as a string"""
     return dt.strftime(cls.TIME_FORMATS[0])
예제 #29
0
def flatten_time(t: datetime.time):
    if t.second:
        return t.strftime('%H:%M:%S')
    else:
        return t.strftime('%H:%M')
예제 #30
0
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))
예제 #31
0
 def to_url(self, value: time) -> str:
     return value.strftime(self.format)
예제 #32
0
def format_time(when: datetime.time, format_str: str = TIME_FORMAT) -> str:
    """Returns a string representing the given datetime.time object.
    If no strftime-compatible format is provided, the default is used."""

    return when.strftime(format_str)
예제 #33
0
파일: _cast.py 프로젝트: flowdas/typeable
def _cast_str_time(cls: Type[str], val: datetime.time, ctx):
    if ctx.time_format == 'iso':
        return cls(val.isoformat())
    else:
        return cls(val.strftime(ctx.time_format))