def get(cinema_api_id: str = None, movie_api_id: str = None, start_day: datetime = None,
         end_day: datetime = None, city: str = None) -> List:
     query = DB.session.query(Screening)
     query = query.filter(Screening.cinema_api_id == cinema_api_id if cinema_api_id else True)
     query = query.filter(Screening.movie_api_id == movie_api_id if movie_api_id else True)
     query = query.filter(Screening.city == city if city else True)
     if start_day:
         start_day = start_day.replace(hour=0, minute=0, second=0, microsecond=0)
         query = query.filter(Screening.date_time > start_day + Yap.DAY_STARTS_AT)
     if end_day:
         end_day = end_day.replace(hour=0, minute=0, second=0, microsecond=0)
         query = query.filter(Screening.date_time <= end_day + Yap.DAY_STARTS_AT)
     query = query.order_by(Screening.date_time)
     return query.all()
def get_next_circadian_color(date: datetime = None) -> (datetime, CircadianColor):
    if date is None:
        date = datetime.datetime.now(LOCAL_TIMEZONE)

    current_color = get_current_circadian_color(date)
    current_color_idx = CIRCADIAN_COLORS_ASC.index(current_color)

    while True:

        if current_color_idx == len(CIRCADIAN_COLORS_ASC) - 1:
            current_color_idx = 0
            next_color = CIRCADIAN_COLORS_ASC[current_color_idx]
            next_date = next_color.trigger_date_function(date + datetime.timedelta(days=1))  # First event tomorrow
        else:
            current_color_idx += 1
            next_color = CIRCADIAN_COLORS_ASC[current_color_idx]
            next_date = next_color.trigger_date_function(date)

        logger.info("Testing next event (%s) after %s", next_color.name, current_color.name)

        if next_color.is_valid_for_date(date):
            break

    logger.info("Next event after %s is %s at %s",
                date.strftime('%Y/%m/%d %I:%M:%S %p'),
                next_color.name,
                next_date.strftime('%Y/%m/%d %I:%M:%S %p'))

    return next_date, next_color
Exemple #3
0
def localise_to_utc(timestamp: datetime) -> datetime:
    """
    Localise the given timestamp to UTC.
    :param timestamp: the timestamp to localise
    :return: the timestamp localised to UTC
    """
    if timestamp.tzinfo is None:
        return pytz.utc.localize(timestamp)
    else:
        return timestamp.astimezone(pytz.utc)
 def time2seconds(t: datetime) -> int:
     """
     converts a datetime to an integer of seconds since epoch
     """
     try:
         return int(t.timestamp())
     except:
         # only implemented in python3.3
         # this is an old compatibility thing
         return t.hour * 60 * 60 + t.minute * 60 + t.second
    def convert_datetime(dt: datetime) -> str:
        """Converts python datetime to MySQL datetime.

        Method converts given python datetime object to MySQL datetime format.

        Args:
            dt: Datetime object in default format.

        Returns:
            Datetime string in MySQL format.
        """
        return dt.strftime('%Y-%m-%d %H:%M:%S')  # Convert to MySQL datetime
Exemple #6
0
 def get_appointments_for_attendee_for_day(attendee: User, date: datetime):
     """
     Gets a list of Appointments for the selected user and date
     :param attendee: User selected
     :param date: Date selected
     :return: apts: list of appointments
     """
     apts = []
     for apt in attendee.get_appointments():
         if date.date() == apt.tstart.date() and not apt.is_in_past():
             apts += [apt]
     return apts
 def get_for_day(day: datetime, city: str) -> List:
     start_day = day.replace(hour=0, minute=0, second=0, microsecond=0)
     end_day = start_day + datetime.timedelta(days=1)
     query = DB.session.query(Screening, Movie, Cinema)
     query = query.filter(Screening.date_time > start_day + Yap.DAY_STARTS_AT)
     query = query.filter(Screening.date_time <= end_day + Yap.DAY_STARTS_AT)
     query = query.filter(Screening.city == city)
     query = query.filter(Screening.cinema_api_id == Cinema.api_id)
     query = query.filter(Screening.movie_api_id == Movie.api_id)
     query = query.filter(Screening.date_time > get_now(city))
     query = query.order_by(Screening.date_time)
     return query.all()
Exemple #8
0
    def delayed_turn_off_timestamp(countdown: int,
                                   current: datetime,
                                   previous: datetime):
        """Update the turn off timestamp only if necessary."""
        if countdown is not None and countdown > 0:
            new = current.replace(second=0, microsecond=0) + \
                  timedelta(minutes=countdown)

            if previous is None:
                return new

            lower = timedelta(minutes=-DELAYED_TURN_OFF_MAX_DEVIATION_MINUTES)
            upper = timedelta(minutes=DELAYED_TURN_OFF_MAX_DEVIATION_MINUTES)
            diff = previous - new
            if lower < diff < upper:
                return previous

            return new

        return None
def get_current_circadian_color(date: datetime = None) -> CircadianColor:
    if date is None:
        date = datetime.datetime.now(LOCAL_TIMEZONE)

    current_color = None

    for color in reversed(CIRCADIAN_COLORS_ASC):
        if color.trigger_date_function(date) < date and color.is_valid_for_date(date):
            current_color = color
            break

    # Note this won't happen so long as first color occurs at midnight
    if current_color is None:
        current_color = CIRCADIAN_COLORS_ASC[-1]

    logger.info("Current event at %s is %s since %s",
                date.strftime('%Y/%m/%d %I:%M:%S %p'),
                current_color.name,
                current_color.trigger_date_function(date).strftime('%Y/%m/%d %I:%M:%S %p'))

    return current_color
Exemple #10
0
def fill_date_fields(template: Template,
                     date: datetime=DateField.TODAY) -> None:
    """ Populate all date fields in the template.

        A 'date' field provides an easy way of putting the current date into a template.

        A date field uses built-in Python date formats, and should look like this:

            '{{ date }}'              - using default formatting
            '{{ date '%d, %b %Y' }}'  - using custom formatting

        See all supported format identifiers here http://strftime.org
    """

    def next_date_field():
        """ Return the next probable date field. """

        return first(fields(template.content, with_name_like='date'))

    field = next_date_field()

    while field is not None:
        # default date format: 07 Oct, 2016
        date_format = '%B %-d, %Y'

        if field.context is not None:
            # a date field can have a custom format
            custom_date_format = dequote(field.context).strip()

            if len(custom_date_format) > 0:
                # if found, we'll use that and let date.strftime handle it
                date_format = custom_date_format

        formatted_date = date.strftime(date_format)

        # populate the include field with the content; or blank if unresolved
        fill(field, formatted_date, template)

        field = next_date_field()
Exemple #11
0
def time_ago(time_in: datetime) -> str:
    """ returns string saying how long ago the time on input was
    """
    now = datetime.datetime.utcnow()
    diff = now - time_in
    sec_diff = int(diff.total_seconds())

    rules = [
        # threshold in seconds, view function, suffix

        (120, lambda x: "", "<2 minutes"),
        (7200, lambda x: int(x / 60),  "minutes"),
        (172800, lambda x: int(x / 3600),  "hours"),
        (5184000, lambda x: int(x / 86400),  "days"),
        # we should provide timezone # but it doesn't really matter here
        (None, lambda x: time_in.date().isoformat(),  ""),

    ]

    for threshold, func, suffix in rules:
        if threshold is None or sec_diff < threshold:
            return "{} {}".format(func(sec_diff), suffix)
    else:
        raise RuntimeError("Unexpected error in time_ago filter,")
Exemple #12
0
 def as_utc_timezone(date_time: datetime) -> datetime:
     """Return a datetime adjusted to the GMT timezone (aka UTC)."""
     return date_time.astimezone(pytz.timezone('GMT'))
def parse_time(date_time: datetime) -> str:
    date_time = date_time.astimezone(dateutil.tz.tzlocal())
    return date_time.strftime('%Y-%m-%d %H:%M:%S')
def FirstOfNextMonth(dt: datetime):
    next_month = dt.replace(day=28) + datetime.timedelta(
        days=4)  # enough to get to the next month, no matter where we start
    return next_month.replace(day=1)
Exemple #15
0
def __date_to_string(date: datetime):
    return date.strftime("%Y%m%d%H%M00 %z")
 def enterabs_dt(self, dt: datetime, priority, func, args=(), kwargs=None):
     kwargs = kwargs if kwargs else {}
     self.sched.enterabs(dt.timestamp(), priority, func, args, kwargs)
Exemple #17
0
 def to_time_str(dt: datetime) -> str:
     return dt.strftime('%H:%M:%S')
Exemple #18
0
def time_unix(a: datetime):
    return int(time.mktime(a.timetuple()) * 1000)
def mysql_friendly_datetime(dt: datetime) -> str:
    """Turns a `datetime` object into a MySQL DATETIME format."""
    return dt.strftime('%y-%m-%d %H:%M:%S.%f')
Exemple #20
0
def Datetime2Ms(duration: datetime) -> int:
    """Convert datetime to integer"""
    return int(round(duration.total_seconds() * 1000))
Exemple #21
0
def convert_to_bloomberg_date(date: datetime) -> str:
    return date.strftime('%Y%m%d')
Exemple #22
0
def chopSeconds(ts: datetime):
    #ts -= datetime.timedelta(seconds=ts.second, microseconds=ts.microsecond)
    #return ts
    return ts.replace(second=0, microsecond=0)
def define_type_of_current_week(day: datetime):
    number = day.isocalendar()[1]
    if number % 2 == 0:
        return True
    else:
        return False
Exemple #24
0
def datetime_to_timestamp(date_time: datetime):
    return str(calendar.timegm(date_time.timetuple()))
Exemple #25
0
def javaTime(d:datetime):
    return d.strftime("%Y-%m-%dT%H:%M:%S.%f")
Exemple #26
0
 def to_str(dt: datetime) -> str:
     return dt.strftime('%Y-%m-%d %H:%M:%S')
 def date_time_to_string(dt: datetime, format: str):
     return dt.strftime(format)
Exemple #28
0
 def to_date_str(dt: datetime) -> str:
     return dt.strftime('%Y-%m-%d')
def FirstOfThisYear(dt: datetime):
    return dt.replace(day=1, month=1)
Exemple #30
0
def get_acessed_date_as_string(d: datetime) -> str:
    date_time = d.strftime("%m/%d/%Y")
    return date_time
Exemple #31
0
def rand_time(start: datetime = datetime.datetime.now(),
              hrs: float = 1) -> datetime:
    stime_ms = (start - datetime.timedelta(hours=hrs)).timestamp()
    etime_ms = start.timestamp()
    rtime_ms = stime_ms + random.random() * (etime_ms - stime_ms)
    return datetime.datetime.fromtimestamp(rtime_ms)
Exemple #32
0
def format_iso_8601_date(value: datetime) -> str:
    return value.strftime('%Y-%m-%dT%H:%M:%SZ')
    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 #34
0
def format_datetime(dt: datetime):
    return dt.strftime('%Y-%m-%dT%H:%M:%S%z')
def EndOfThisMonth(dt: datetime):
    next_month = dt.replace(day=28) + datetime.timedelta(
        days=4)  # enough to get to the next month, no matter where we start
    return next_month - datetime.timedelta(days=next_month.day)
Exemple #36
0
def j2_filter_date(date: datetime):
    return date.strftime('%H:%M:%S.%f')
Exemple #37
0
 def last_change_after(self, last_change: datetime):
     self.add_options({"after": last_change.strftime("%Y%m%d%H%M%S")})
def FirstOfThisMonth(dt: datetime):
    return dt.replace(day=1)
Exemple #39
0
def getDate(date: datetime, sep: str = "", frmt="ymd") -> str:
    if frmt == "ymd":
        sFrmt = "%Y" + sep + "%m" + sep + "%d"
    elif frmt == "dmy":
        sFrmt = "%d" + sep + "%m" + sep + "%Y"
    return date.strftime(sFrmt)
Exemple #40
0
 def to_epoch(dt: datetime) -> int:
     return int(dt.timestamp()) * 1000
Exemple #41
0
 def as_legislation_timezone(date_time: datetime) -> datetime:
     """Return a datetime adjusted to the legislation timezone."""
     return date_time.astimezone(
         pytz.timezone(current_app.config.get('LEGISLATIVE_TIMEZONE')))
 def get_transactions(self, from_date: datetime):
     url = [self.TRANSACTIONS_URI, '?from=', from_date.strftime("%Y-%m-%d")]
     response = self.__get_response__(''.join(url), "2")
     return transactions_from_dict(json.loads(response))
def FirstOfNextYear(dt: datetime):
    return dt.replace(day=1, month=1, year=dt.year + 1)
 def get_activities(self, from_date: datetime):
     url = [self.ACTIVITIES_URI, '?from=', from_date.strftime("%Y-%m-%d")]
     response = self.__get_response__(''.join(url), "3")
     return activities_from_dict(json.loads(response))
Exemple #45
0
def jira_date_str(date: datetime) -> str:
    # TODO: Why does the 'Z' thing work and does this mess up stats?
    # NOTE: We chomp the nano-seconds, but keep the milli-seconds
    return date.strftime(VELOCITY_PARM_DATE_FORMAT)[:-3] + 'Z'
Exemple #46
0
def split(dt: _datetime) -> Tuple[_datetime.date, _datetime.time]:
    """Split a datetime into date and time components.  Useful over calling
    .date() and .time() methods, since that dumps tzinfo for the time component."""
    time_ = time(dt.hour, dt.minute, dt.second, dt.microsecond, dt.tzinfo)
    return dt.date(), time_
Exemple #47
0
 def last_change_before(self, last_change: datetime):
     self.add_options({"before": last_change.strftime("%Y%m%d%H%M%S")})