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 china_tz(dt: datetime) -> datetime:
    """
    返回东八区的中国时间
    :param dt:
    :return:
    """
    if dt.tzinfo is not None:
        return dt.astimezone(local_tz)
    return local_tz.localize(dt, is_dst=None)
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)
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 to_utc(self, value: datetime):
        """
        Convert datetime to UTC timezone.

        :param value: datetime
        :return: datetime in UTC
        """
        if not value.tzinfo:
            return self.to_utc(value.replace(tzinfo=self.timezone))
        else:
            return value.astimezone(tz.utc)
Exemple #6
0
    def to_utc(self, value: datetime):
        """
        Convert datetime to UTC timezone.

        :param value: datetime
        :return: datetime in UTC
        """
        if not value.tzinfo:
            return UTC.localize(value)
        else:
            return value.astimezone(UTC)
Exemple #7
0
def insert_assignment(self, user_id: int, course_id: int, name: str,
                      deadline: datetime, reveal: datetime,
                      files: list) -> int:
    """Inserted the given fields to the database. If Reveal is null, current time is used
    The files given need to be able to read with.read, and need the filename property. seek(0) is called before reading
    All given dates are converted to UTC before insert (so they shouldn't be naive)

    Arguments:
        user_id {int} -- [user id]
        course_id {int} -- [course id]
        name {str} -- [name]
        deadline {datetime} -- [deadline]
        reveal {datetime} -- [reveal]
        files {list} -- [description]

    Returns:
        [id] -- [pk of the inserted assignment]
    """
    d = None
    if deadline is not None:
        d = deadline.astimezone(datetime.timezone.utc)

    if reveal is not None:
        r = reveal.astimezone(datetime.timezone.utc)
    else:
        r = datetime.datetime.utcnow()

    sql = self.assignment.insert().values(deadline=d,
                                          reveal=r,
                                          course_id=course_id,
                                          name=name)
    with self.engine.connect() as conn:
        self.logger.info("Inserting  assignment for user %s (course %s) ",
                         user_id, course_id)
        rs = conn.execute(sql)
        id = rs.inserted_primary_key[0]
        self.logger.info("Insert success! assignment id: %s", id)
        self.insert_files(user_id, files, assignment_id=id, task_id=None)

        rs.close()
    return id
Exemple #8
0
def datetime_to_utc_as_str(target: datetime) -> str:
    """Make datetime string representation in UTC timezone.

    Return:
        String representation of without and taking into the account time zone formatted in UTC timezone.
            If no timezone - UTC timezone will be added.
        Examples:
            - 2020-04-03 05:00:07.086149+00:00 -> 2020-04-03 05:00:07.086149+00:00
            - 2020-04-03 05:00:07.086149+02:00 -> 2020-04-03 03:00:07.086149+00:00
    """
    if target.tzinfo is None or not target.utcoffset() or target.tzinfo == pytz.utc:
        target = target.replace(tzinfo=datetime.timezone.utc)
        return target.isoformat()

    # to this part we should get only datetime with particular timezone offset
    res = target.astimezone(pytz.utc).replace(tzinfo=datetime.timezone.utc)
    return res.isoformat()
def to_falkonry_datetime_str(dt:datetime,format=TimeFormats.ISO):
    # if not timezone aware raise exception
    if(dt.tzinfo is None or dt.tzinfo.utcoffset(dt) is None):
        raise ValueError("dt must be timezone aware")
    # convert to utc
    utc_dt=dt.astimezone(timezone.utc)
    # Falkonry only accepts 6 figures (microsecs)
    if(format==TimeFormats.SECS):
        return str(round(utc_dt.timestamp()))
    elif(format==TimeFormats.MILLIS):
        return str(round(utc_dt.timestamp()*1000))
    elif(format==TimeFormats.MICROS):
        return str(round(utc_dt.timestamp()*1e6))
    elif(format==TimeFormats.NANOS):
        return str(round(utc_dt.timestamp()*1e9))
    else:
        # Falkonry only accepts 6 figures (microsecs)
        return datetime.strftime(utc_dt,"%Y-%m-%dT%H:%M:%S.%fZ")
Exemple #10
0
def datetime_to_bytes(obj: datetime) -> bytes:
    """Convert a datetime in to bytes
    Args:
        obj: datetime to convert in to bytes
    Returns:
        bytes representing the datetime
    """
    # use seconds since epoc in order to properly compare different time zones
    # https://docs.python.org/3.8/library/datetime.html#datetime.datetime.timestamp
    # if tz aware convert to utc before extracting the raw time
    if obj.tzinfo is not None:
        # we trust this to be a well behaved float (not swapping 0.0 for -0.0, so use bytes_from_repr directly
        new_time = obj.astimezone(timezone.utc)
    else:
        # if non-tz aware then we can just pull all the raw time values
        new_time = obj
    return str_to_bytes(
        "{} {} {} {} {} {} {}".format(new_time.year, new_time.month, new_time.day, new_time.hour, new_time.minute,
                                      new_time.second, new_time.microsecond))
Exemple #11
0
    def convert_to_julian(self, date: datetime):
        """
        Convert date from Gregorian to Julian calendar.

        :param date: Date represented as datetime object.
        :type date: datetime
        :param daylightsaving: Flag if hour needs day light saving adjust.
        :rtype: int
        """

        # Transform to UTC timezone.
        date = date.astimezone(pytz.timezone('UTC'))
        # Aggregate hours, mins, secs as required by swisseph.
        aggregate_time = date.hour + (date.minute / 60.0) + (date.second /
                                                             3600.0)
        self.time = aggregate_time
        # Set calendar type to use based on time options.
        calflag = astrology.SE_GREG_CAL

        # Convert date to Julian Day.
        julian_date = swisseph.julday(date.year, date.month, date.day,
                                      aggregate_time, calflag)

        return julian_date
def _tz_convert_to_chinese(dt: datetime):
    chinese_zone = pytz.timezone('Asia/Shanghai')
    dt = chinese_zone.localize(dt) if not dt.tzinfo else dt.astimezone(
        chinese_zone)
    return dt
Exemple #13
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 parse_time(date_time: datetime) -> str:
    date_time = date_time.astimezone(dateutil.tz.tzlocal())
    return date_time.strftime('%Y-%m-%d %H:%M:%S')
Exemple #15
0
def to_local_datetime(dt: datetime) -> datetime:
    local_zone = get_local_timezone()
    if dt.tzinfo is None:
        dt = dt.replace(tzinfo=datetime.timezone.utc)
    local_dt = dt.astimezone(local_zone)
    return local_dt
Exemple #16
0
def _convert_unix_to_iso8610(unix_timestamp: datetime) -> str:

    iso_timestamp = unix_timestamp.astimezone(tz.UTC).isoformat()

    return iso_timestamp
Exemple #17
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'))