Exemple #1
0
 def is_end_of_month(dt_obj: datetime) -> bool:
     """ Is this `datetime` object the last day of it's month?"""
     if dt_obj.day not in (28, 29, 30, 31):
         return False
     try:
         dt_obj.replace(day=dt_obj.day + 1)
     except ValueError:
         return True
     else:
         return False
 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()
Exemple #3
0
def local_datetime_to_utc_as_str(target: datetime) -> str:
    """Make datetime string representation in UTC timezone. Use it just for local time!

    Return:
         String representation of without and taking into the account time zone formatted in UTC timezone.
            Do not make changes if already in UTC timezone or does not have any.
    """
    if target.tzinfo is None or not target.utcoffset() or target.tzinfo == pytz.utc:
        target = target.replace(tzinfo=datetime.timezone.utc)
        return target.isoformat()

    utc_offset_timedelta = datetime.datetime.utcnow() - datetime.datetime.now()
    target = target.replace(tzinfo=datetime.timezone.utc)
    result_utc_datetime = target + utc_offset_timedelta
    return result_utc_datetime.isoformat()
 def last_day_of_month(any_day: datetime) -> datetime:
     # this will never fail
     # get close to the end of the month for any day, and add 4 days 'over'
     next_month = any_day.replace(day=28) + datetime.timedelta(days=4)
     # subtract the number of remaining 'overage' days to get last day of current month,
     # or said programattically said, the previous day of the first of next month
     return next_month - datetime.timedelta(days=next_month.day)
Exemple #5
0
    def UIActionsOfDayList(self, day: datetime) -> list:
        '''create list of actions at given day in UI friendly format
           return
              created list'''
        dstart = day.replace(hour=0, minute=0, second=0, microsecond=0)
        dend = dstart + timedelta(days=1)

        dcal = self.findBetween(dstart, dend)

        dlist = list()
        for a in dcal.__actions:
            td = (a._start - dstart)
            mi = round(td.total_seconds() / 60)
            d = {
                'long':
                f"{a._start.strftime('%H:%M')} {a._task._name} [{a._task._projectName}]",
                'task': a._task._name,
                'prj': a._task._projectName,
                'id': a._task._id,
                'color': a._task._farbe,
                'minute': mi,
                'time': a._start.strftime('%H:%M'),
                'date': a._start.strftime('%Y-%m-%d')
            }

            # print(d)
            dlist.append(d)

        return dlist
    def time_is_between(hass, target_dt: datetime, start_time: str,
                        end_time: str) -> bool:
        """Generalization of AppDaemon's now_is_between method."""
        start_time_dt = hass.parse_time(start_time)  # type: datetime
        end_time_dt = hass.parse_time(end_time)  # type: datetime
        start_dt = target_dt.replace(hour=start_time_dt.hour,
                                     minute=start_time_dt.minute,
                                     second=start_time_dt.second)
        end_dt = target_dt.replace(hour=end_time_dt.hour,
                                   minute=end_time_dt.minute,
                                   second=end_time_dt.second)

        if end_dt < start_dt:
            # Spans midnight
            if target_dt < start_dt and target_dt < end_dt:
                target_dt = target_dt + timedelta(days=1)
            end_dt = end_dt + timedelta(days=1)
        return start_dt <= target_dt <= end_dt
 def to_utc_datetime(value: datetime):
     if value is None:
         return value
     elif type(value) == datetime:
         if value.tzinfo is None:
             value = value.replace(tzinfo=UTC)
         return value
     else:
         return DateTimeConverter.to_nullable_datetime(value)
Exemple #8
0
def delete_rates_older_than(date_time: datetime):
    sql_date = date_time.replace(microsecond=0)
    conn = sqlite3.connect(CONF.db_name, detect_types=sqlite3.PARSE_DECLTYPES | sqlite3.PARSE_COLNAMES)
    curs = conn.cursor()
    try:
        curs.execute("DELETE FROM rates WHERE date_time < '{}' ".format(sql_date))
        conn.commit()
    finally:
        curs.close()
        conn.close()
 async def sendGuildChannel(self, guild: discord.Guild, str: str, dt: datetime):
     if await self.audit_log_channel.get_ch(guild) is False:
         logger.debug(self.audit_log_channel.alc_err)
         return
     else:
         to_channel = self.audit_log_channel.channel
     dt_tz = dt.replace(tzinfo=datetime.timezone.utc)
     dt_jst = dt_tz.astimezone(datetime.timezone(datetime.timedelta(hours=9))).strftime('%Y/%m/%d(%a) %H:%M:%S')
     msg = '{1}: {0}'.format(str, dt_jst)
     await to_channel.send(msg)
Exemple #10
0
 def average_for_date(self, data_type: GFitDataType, dt: datetime) -> float:
     """
     This function will calculate the boundaries for the given date for you
     :param dt: A specific datetime
     :param data_type: A data type from GFitDataType
     :return: the average for the specified datatype for the given date
     """
     begin = dt.replace(hour=0, minute=0, second=0, microsecond=0)
     end = begin + datetime.timedelta(days=1)
     return self._avg_for_response(data_type, begin, end)
Exemple #11
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 #12
0
def add_tz(dt: datetime, zone: str) -> datetime:
    """add_tz datetime doesnt assign a time zone.  This function shows how to do it.

    Args:
        dt (datetime): original datetime
        zone (str): desired zone 

    Returns:
        datetime: a new datetime with the zone assigned
    """

    return dt.replace(tzinfo=tz.gettz(zone))
 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 #14
0
    def round_time(dt: datetime, resolution: datetime.timedelta):
        """
        Rounds a timestamp by a given resolution.
        Function is based on the following answer on stackoverflow: https://stackoverflow.com/a/31005978

        :param dt: Timestamp to round
        :param resolution: Precision of the output
        :return: A new timestamp rounded to the given precision
        """
        round_to = resolution.total_seconds()
        seconds = (dt.replace(tzinfo=None) - dt.min).seconds
        rounding = (seconds + round_to / 2) // round_to * round_to
        return dt + datetime.timedelta(0, rounding - seconds, -dt.microsecond)
    def __getDayText(self, date_today: datetime, date_requested: datetime):

        date_requested = date_requested.replace(hour=0,
                                                minute=0,
                                                second=0,
                                                microsecond=0)
        date_today = date_today.replace(hour=0,
                                        minute=0,
                                        second=0,
                                        microsecond=0)

        diff_in_days = (date_requested - date_today).days

        if (diff_in_days <= 0):
            return "heute"
        elif (diff_in_days == 1):
            return "morgen"
        else:
            weekDays = ("Montag", "Dienstag", "Mittwoch", "Donnerstag",
                        "Freitag", "Samstag", "Sonntag")

            weekday_name = weekDays[date_requested.weekday()]
            return "am {}".format(weekday_name)
Exemple #16
0
def create_mhl(start: datetime):
    start = start.replace(microsecond=0).isoformat() + "Z"
    finish = datetime.datetime.utcnow().replace(microsecond=0).isoformat() + "Z"
    new_mhl = E.hashlist(
        E.creatorinfo(
            E.name(get_user_display_name()),
            E.username(getpass.getuser()),
            E.hostname(gethostname()),
            E.tool("o/COPY"),
            E.startdate(start),
            E.finishdate(finish),
        ),
        version="1.1",
    )
    return new_mhl
Exemple #17
0
    def listActionsOfDay(self, day: datetime) -> list:

        dstart = day.replace(hour=0, minute=0, second=0, microsecond=0)
        dend = dstart + timedelta(days=1)

        dcal = self.findBetween(dstart, dend)

        dlist = list()
        for a in dcal.__actions:
            td = (a._start - dstart)
            mi = round(td.total_seconds() / 60)
            dlist.append(
                (mi, a._task._farbe, a._start.strftime("%H:%M"), a._task._name,
                 a._task._projectName, a._start.strftime("%Y-%m-%d")))

        return dlist
Exemple #18
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()
Exemple #19
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(microsecond=0) + timedelta(seconds=countdown)

            if previous is None:
                return new

            lower = timedelta(seconds=-DELAYED_TURN_OFF_MAX_DEVIATION_SECONDS)
            upper = timedelta(seconds=DELAYED_TURN_OFF_MAX_DEVIATION_SECONDS)
            diff = previous - new
            if lower < diff < upper:
                return previous

            return new

        return None
Exemple #20
0
    def get_late_list(self,
                      date: datetime,
                      start_work_hour: int,
                      reverse=True) -> list:
        user_is_late = []
        work_hour = date.replace(hour=start_work_hour, minute=0, second=0)

        for user in self.get_list():
            if user.is_fired():
                continue
            time = user.time
            if time.is_absent(date):
                continue
            if time.get_first(date) > work_hour:
                user_is_late.append(user)

        return sorted(user_is_late,
                      key=lambda k: k.time.get_first(date),
                      reverse=reverse)
Exemple #21
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
Exemple #22
0
def time_delta(src: datetime,
               years: int = 0,
               months: int = 0,
               weeks: int = 0,
               days: int = 0,
               hours: int = 0) -> datetime:
    """对src进行时间差的计算。 可以计算年月周日时的时间差,可以同时指定,如果设置为负数表示求前一个时间点,如果
    设置为正数,表示求将来的时间点。

    :param src: 源时间点,type: datetime
    :param years: 年份的差值, type: int
    :param months: 月份的差值, type: int
    :param weeks: 周的差值, type: int
    :param days: 日的差值, type: int
    :param hours: 小时的差值, type: int

    :return: 计算后的datetime的对象
    """

    # 利用timedelta先计算时,天,周的差值
    src += datetime.timedelta(hours=hours, days=days, weeks=weeks)
    # 计算月的差值
    dy, dm = divmod(src.month + months, TimeConstant.MAX_MONTH)
    # 如果余数刚好是0(刚好被12整除),那么是上一年的12月份
    month = dm or TimeConstant.MAX_MONTH
    dy = src.year + dy + years
    # 如果余数刚好是0(刚好被12整除),那么是上一年的12月份
    year = dy if dm else dy - 1
    # 如果源时间是月份的最后一天,需要判断计算后的月份是否有31号(如果是2月,还需要判断是否是闰年)
    day = src.day
    if src.day == TimeConstant.MAX_DAY:
        day = TimeConstant.MDAYS[month]
    if month == TimeConstant.LEAP_MONTH and src.day > TimeConstant.MDAYS[
            TimeConstant.LEAP_MONTH]:
        day = TimeConstant.LEAP_MDAYS[
            TimeConstant.LEAP_MONTH] if calendar.isleap(
                year) else TimeConstant.MDAYS[TimeConstant.LEAP_MONTH]
    return src.replace(year=year, month=month, day=day)
def respond_date_in_request(*, request: YandexRequest, context: dict,
                            date: datetime, database_client):
    # Save to database for specified time
    # Clear context
    # Say Сохранено

    update_user_table(
        database_client=database_client,
        event_time=date.replace(
            tzinfo=dateutil.tz.gettz(request.timezone)).astimezone(
                dateutil.tz.gettz('UTC')),
        foods_dict=context['foods'],
        user_id=request.user_guid,
        utterance=context['utterance'])

    return construct_yandex_response_from_yandex_request(
        yandex_request=request,
        text=f'Сохранено за {date.date()}. Чтобы посмотреть список '
        f'сохраненной еды, спросите меня что Вы ели',
        tts='Сохранено',
        end_session=False,
        buttons=[],
    )
Exemple #24
0
def next_step(instant: datetime, step: int):
    """
    Round to the next round multiple of step seconds in the minute.

    0 <= step <= 60

    >>> inst = datetime.datetime(2020, 2, 20, 9, 30, 33)
    >>> next_step(inst, 15)
    datetime.datetime(2020, 2, 20, 9, 30, 45)
    >>> inst = datetime.datetime(2020, 2, 20, 9, 30, 30)
    >>> next_step(inst, 15)
    datetime.datetime(2020, 2, 20, 9, 30, 45)
    >>> inst = datetime.datetime(2020, 2, 20, 9, 30, 55)
    >>> next_step(inst, 15)
    datetime.datetime(2020, 2, 20, 9, 31)
    >>> next_step(inst, 60)
    datetime.datetime(2020, 2, 20, 9, 31)
    """
    return instant.replace(
        minute=instant.minute + step * (1 + instant.second // step) // 60,
        second=(step * (1 + instant.second // step)) % 60,
        microsecond=0
    )
Exemple #25
0
    def removeIDAtTime(self, id_, time: datetime) -> Task:
        ''' delete the action with given id and time
         return:
             found action
             None if nothing found'''

        time = time.replace(second=0, microsecond=0)

        if self.__notsorted:
            self.sort()

        for i in range(len(self.__actions) - 1, 0, -1):
            if self.__actions[i]._start < time:
                break
            if self.__actions[i]._start == time:
                if self.__actions[i]._id == id_:
                    a = self.__actions[i]
                    self.__actions.remove(self.__actions[i])
                    self.__dirty = True
                    return a
        'Wenn die Schleife komplett durchläuft dann wurde nichts gefunden'

        return None
def iterate_month(date: datetime, direction: int = 1):
    # handle subtract 1 month
    if direction == 0:
        # Handle edge case
        if date.month == 1:
            date = date.replace(month=12)
            date = date.replace(year=date.year-1)
        else:
            date = date.replace(month=date.month-1)

    # Handle add 1 month
    else:
        # Handle edge case
        if date.month == 12:
            date = date.replace(month=1)
            date = date.replace(year=date.year+1)
        else:
            date = date.replace(month=date.month+1)

    return date
def FirstOfNextYear(dt: datetime):
    return dt.replace(day=1, month=1, year=dt.year + 1)
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 #29
0
def chopSeconds(ts: datetime):
    #ts -= datetime.timedelta(seconds=ts.second, microseconds=ts.microsecond)
    #return ts
    return ts.replace(second=0, microsecond=0)
    def epg(self,
            channels,
            from_date: datetime,
            days: int = 7) -> Dict[str, List[Programme]]:
        print('Generating EPG for %d days' % days)
        self._login()
        ret = {}
        channel_ids = list(map(lambda ch: str(ch.id), channels))

        from_date = from_date.replace(hour=0,
                                      minute=0,
                                      second=0,
                                      microsecond=0)
        to_date = from_date + datetime.timedelta(days=days + 1)
        now = datetime.datetime.utcnow()

        days = int((to_date - from_date).days)

        for n in range(days):

            current_day = from_date + datetime.timedelta(n)
            filter = 'startTime=ge=%sT00:00:00.000Z;startTime=le=%sT00:59:59.999Z' % (
                current_day.strftime("%Y-%m-%d"),
                (current_day +
                 datetime.timedelta(days=1)).strftime("%Y-%m-%d"))

            fetch_more = True
            offset = 0
            while fetch_more:
                resp = self._get('https://skgo.magio.tv/v2/television/epg',
                                 params={
                                     'filter': filter,
                                     'limit': '20',
                                     'offset': offset * 20,
                                     'list': 'LIVE'
                                 },
                                 headers=self._auth_headers())

                fetch_more = len(resp['items']) == 20
                offset = offset + 1

                for i in resp['items']:
                    for p in i['programs']:
                        channel = str(p['channel']['id'])
                        if channel not in channel_ids:
                            continue

                        if channel not in ret:
                            ret[channel] = []

                        programme = self._programme_data(p['program'])
                        programme.start_time = datetime.datetime.utcfromtimestamp(
                            p['startTimeUTC'] / 1000)
                        programme.end_time = datetime.datetime.utcfromtimestamp(
                            p['endTimeUTC'] / 1000)
                        programme.duration = p['duration']
                        programme.is_replyable = (
                            programme.start_time >
                            (now - datetime.timedelta(days=7))) and (
                                programme.end_time < now)

                        ret[channel].append(programme)
        return ret
Exemple #31
0
def get_date_rage_for_scheduling(date: datetime):
    start_date = date.replace(hour=0, minute=0, second=0)
    end_date = date.replace(hour=DEADLINE_HOUR_TO_SEND_SCHEDULE,
                            minute=0,
                            second=0)
    return DateRange(start=start_date, end=end_date, is_empty=False)
Exemple #32
0
 def LocalTimestamp(theDate: datetime = datetime.datetime.now()
                    ) -> datetime:
     utc_offset_sec = time.altzone if time.localtime(
     ).tm_isdst else time.timezone
     return theDate.replace(tzinfo=datetime.timezone(
         offset=datetime.timedelta(seconds=-utc_offset_sec)))
Exemple #33
0
 def UTCTimestamp(theUTCDate: datetime = datetime.datetime.utcnow()
                  ) -> datetime:
     return theUTCDate.replace(tzinfo=datetime.timezone.utc)