Exemple #1
0
    def has_available_slots(office: Office, start_time: datetime,
                            end_time: datetime, service: Service):
        """Return if there is any available slot for the time period for the office."""
        start_time = start_time.astimezone(
            pytz.timezone(office.timezone.timezone_name))
        end_time = end_time.astimezone(
            pytz.timezone(office.timezone.timezone_name))

        available_day_slots = AvailabilityService.get_available_slots(
            office=office,
            days=[start_time],
            format_time=False,
            service=service)

        has_available_slot = False
        for slot in available_day_slots[start_time.strftime(
                '%m/%d/%Y')]:  # Iterate the only item from the list
            # Because services can be artbitary duration, we just check if times fall within duration
            # e.g slot is 8-9, but start_time/end_time are 8:30-8:45.
            # We do NOT check across slots, only within an individual slot
            if slot['start_time'] <= start_time.time(
            ) and slot['end_time'] >= end_time.time():
                has_available_slot = True

        return has_available_slot
Exemple #2
0
    def __init__(self, config, sim_st: datetime, all_sampling_data, all_future_data):
        self.logger = logging.getLogger(self.__class__.__name__)

        self.config = config

        self.sim_root = self.config.sim_root + sim_st.date().isoformat() + "/" + sim_st.time().isoformat() + "/"

        self.params_root = self.config.params_output_root + sim_st.date().isoformat() + "/"
        pathlib.Path(self.params_root).mkdir(parents=True, exist_ok=True)

        sim_logs_dir = self.config.sim_logs_root + sim_st.date().isoformat() + "/"

        pathlib.Path(sim_logs_dir).mkdir(parents=True, exist_ok=True)

        self.sim_logs_path = sim_logs_dir + sim_st.time().isoformat() + ".log"

        self.sim_st = sim_st

        self.sampling_window_start_time = sim_st - timedelta(seconds=self.config.sampling_window)
        self.sampling_window_end_time = sim_st

        self.orderbook_window_start_time = sim_st - datetime.timedelta(seconds=self.config.orderbook_window)
        self.orderbook_window_end_time = sim_st

        self.all_sampling_data = all_sampling_data
        self.all_future_data = all_future_data

        self.graphing = Graphing(config, "Backtest @ " + sim_st.isoformat())
def check_if_available(person: int, service: int, date_time: datetime) -> bool:
    bool_list = []
    current_reservations = Reservation.objects.filter(user=person,
                                                      date=date_time.date())
    service = Service.objects.get(id=service)
    duration = service.duration
    start_time = date_time.time()
    end_time = date_time.time() + datetime.timedelta(minutes=duration)
    for reservation in current_reservations:
        reservation_end_time = reservation.start_time + datetime.timedelta(
            minutes=duration)
        bool_list.append(
            reservation.start_time <= start_time <= reservation_end_time
            or reservation.start_time <= end_time <= reservation_end_time)
    if bool_list:
        return True not in bool_list
    else:
        return True
Exemple #4
0
    def has_available_slots(office: Office, start_time: datetime,
                            end_time: datetime):
        """Return if there is any available slot for the time period for the office."""
        start_time = start_time.astimezone(
            pytz.timezone(office.timezone.timezone_name))
        end_time = end_time.astimezone(
            pytz.timezone(office.timezone.timezone_name))

        available_day_slots = AvailabilityService.get_available_slots(
            office=office, days=[start_time], format_time=False)

        has_available_slot = False
        for slot in available_day_slots[start_time.strftime(
                '%m/%d/%Y')]:  # Iterate the only item from the list
            if slot['start_time'] == start_time.time(
            ) and slot['end_time'] == end_time.time():
                has_available_slot = True

        return has_available_slot
Exemple #5
0
def updateTimeIndex(severityEntry:dict, accident:dict,accidentDate: datetime, )->None:
    """
    Actualiza las entradas del indice Time.
        parametros:
            severityEntry(OrderedMap): Contiene un TimeIndex
            accident(dict): Contiene la informacion acerca del accidente

    """
    id = accident['ID']
    accidentTime = blockTime(accidentDate.time())

    entryExist = om.contains(severityEntry,accidentTime)
    if entryExist:
        timeEntry = om.get(severityEntry, accidentTime)
        timeEntry = me.getValue(timeEntry)
    else:
        timeEntry = newIDList()
        om.put(severityEntry,accidentTime,timeEntry)
    
    lt.addFirst(timeEntry['idList'],id)
    timeEntry['size'] += 1
def check_if_any_collisions(person: int, service: int, date_time: datetime, client: int = None) -> \
        Union[bool, Dict[str, bool]]:
    current_reservations = Reservation.objects.filter(user=person,
                                                      date=date_time.date())
    service = Service.objects.get(id=service)
    duration = service.duration
    start_time = date_time.time()
    end_time = (datetime.datetime.combine(datetime.date.today(), start_time) +
                datetime.timedelta(minutes=duration)).time()
    time_range = [
        (reservation.start_time,
         (datetime.datetime.combine(datetime.date.today(),
                                    reservation.start_time) +
          datetime.timedelta(minutes=reservation.service.duration)).time())
        for reservation in current_reservations
    ]
    no_collisions_with_current_reservations = check_time_collisions(
        time_range, start_time, end_time)
    no_collisions_with_client_reservations = True
    if client is not None:
        client_reservations = Reservation.objects.filter(client=client,
                                                         date=date_time.date())
        time_range = [
            (reservation.start_time,
             (datetime.datetime.combine(datetime.date.today(),
                                        reservation.start_time) +
              datetime.timedelta(minutes=reservation.service.duration)).time())
            for reservation in client_reservations
        ]
        no_collisions_with_client_reservations = check_time_collisions(
            time_range, start_time, end_time)

    if no_collisions_with_current_reservations and no_collisions_with_client_reservations:
        return True
    else:
        return {
            'current_reservations': no_collisions_with_current_reservations,
            'client_reservations': no_collisions_with_client_reservations
        }
    def _filter_stop_times_window(self, stop_times: list,
                                  window_start: datetime,
                                  window_end: datetime) -> list:
        """
        This method will only retain the stop times in the given time window
        :param stop_times: The list of stop times to filter.
        :param window_start: The start of the time window.
        :param window_end: End of the time window
        :return: The filtered list
        """
        logging.debug("Filtering stop times")

        # Check if the time window spans across midnight
        window_crosses_midnight = window_end.date() > window_start.date()
        # Calculate the seconds from midnight. This way we can do all later comparisons using integers
        window_start_secs_since_midnight = window_start.time().hour * 3600 \
                                           + window_start.time().minute * 60 \
                                           + window_start.time().second

        window_end_secs_since_midnight = window_end.time().hour * 3600 \
                                         + window_end.time().minute * 60 \
                                         + window_end.time().second

        # Get the day before the start date, needed to check if a trip that spans multiple days was active on this day.
        day_before_start = window_start.date() - timedelta(days=1)

        filtered_stop_times = list()
        for stop_time in stop_times:
            # We already calculated the seconds from midnight in the StopTimesCache.
            secs_since_midnight = stop_time['departure_seconds']
            # The first, easy, check is to see if the time lies between the start and end time.
            # If this fails, we can skip all other checks
            if not self._is_time_in_window(secs_since_midnight,
                                           window_start_secs_since_midnight,
                                           window_end_secs_since_midnight):
                continue

            # Alright, so the time is valid. Is the trip actually ran on that day? Get the service id so we can check
            trip = self._trips_cache.get_trip(stop_time['trip_id'])
            service_id = trip['service_id']

            # Get the hour part from the time. If it is more than 23, it is a trip that started the day before.
            hour_int = secs_since_midnight // 3600

            # This is a trip that started the same day
            if hour_int < 24:
                # If the window doesn't cross midnight, the departure date is the same as the date of the window start.
                # Check if the service_id is active that day
                if not window_crosses_midnight \
                        and self._calendar_dates_cache.is_serviced(service_id, window_start.date()):
                    filtered_stop_times.append(stop_time)
                # If it crosses midnight, we need to determine the departure date first
                elif window_crosses_midnight:
                    # We have constrained the time window to no more than 24h. This means that, if the time window
                    # crosses midnight, the end time will lie before the start time. This simplifies the following tests
                    if secs_since_midnight >= window_start_secs_since_midnight:
                        if self._calendar_dates_cache.is_serviced(
                                service_id, window_start.date()):
                            filtered_stop_times.append(stop_time)
                    else:
                        if self._calendar_dates_cache.is_serviced(
                                service_id, window_start.date()):
                            filtered_stop_times.append(stop_time)
            # This is a trip that started the day before (it's past midnight),
            # check if it was active on the day it started
            elif hour_int >= 24:
                if not window_crosses_midnight and self._calendar_dates_cache.is_serviced(
                        service_id, day_before_start):
                    filtered_stop_times.append(stop_time)
                # Alright, so the window crosses midnight and this trip started the day before.
                # Since this trip planner is restricted to 1-day intervals, we know the day before is start date
                elif window_crosses_midnight:
                    # We have constrained the time window to no more than 24h. This means that, if the time window
                    # crosses midnight, the end time will lie before the start time. This simplifies the following tests
                    # First day. Comparison corrects for the 24h offset since the hour part is larger than 24h
                    if secs_since_midnight - 86400 >= window_start_secs_since_midnight:
                        if self._calendar_dates_cache.is_serviced(
                                service_id, day_before_start):
                            filtered_stop_times.append(stop_time)
                    # Second day
                    else:
                        if self._calendar_dates_cache.is_serviced(
                                service_id, window_start.date()):
                            filtered_stop_times.append(stop_time)
        return filtered_stop_times
Exemple #8
0
def func_extract_time(some_date: datetime) -> Callable:
    return lambda: some_date.time()
Exemple #9
0
 def fillTrainTime(self, departureTime: datetime):
     time = departureTime.time()
     seconds = (time.hour * 60 + time.minute) * 60 + time.second
     approximation = seconds - (seconds % TIME_INTERVAL)
     self.trainX[self.trainRowsIndex][self.columns[approximation]] = 1
Exemple #10
0
def format_time_for_request(time_datetime: datetime) -> str:
    time = time_datetime.time().strftime('%H:%M:%S')
    date = time_datetime.date().strftime('%Y-%m-%d')
    request_string = date + 'T' + time
    return request_string