Python datetime.datetime.html() Examples

The following are 30 code examples of datetime.datetime.html(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module datetime.datetime , or try the search function .
Example #1
Source File: node.py    From BlueSTSDK_Python with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def characteristic_has_other_notifying_features(self, characteristic, feature):
        """Check whether a characteristic has other enabled features beyond the
        given one.

        Args:
            characteristic (Characteristic): The BLE characteristic to check.
            Refer to
            `Characteristic <https://ianharvey.github.io/bluepy-doc/characteristic.html>`_
            for more information.
            feature (:class:`blue_st_sdk.feature.Feature`): The given feature.

        Returns:
            True if the characteristic has other enabled features beyond the
            given one, False otherwise.
        """
        with lock(self):
            features = self._get_corresponding_features(
                characteristic.getHandle())
        for feature_entry in features:
            if feature_entry == feature:
                pass
            elif feature_entry.is_notifying():
                return True
        return False 
Example #2
Source File: node.py    From BlueSTSDK_Python with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def characteristic_can_be_notified(self, characteristic):
        """Check if a characteristics can be notified.

        Args:
            characteristic (Characteristic): The BLE characteristic to check.
            Refer to
            `Characteristic <https://ianharvey.github.io/bluepy-doc/characteristic.html>`_
            for more information.

        Returns:
            bool: True if the characteristic can be notified, False otherwise.
        """
        try:
            if characteristic is not None:
                with lock(self):
                    return "NOTIFY" in characteristic.propertiesToString()
            return False
        except BTLEException as e:
            self._unexpected_disconnect() 
Example #3
Source File: qt.py    From imperialism-remake with GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, *args, **kwargs):
        """
        We initialize the timer and set the update interval (one minute) and start it and update the clock at least
        once.
        """
        super().__init__(*args, **kwargs)

        # customize format if desired (https://docs.python.org/3.5/library/datetime.html#strftime-strptime-behavior)
        self.time_format = '%H:%M'

        # initial update
        self.update_clock()

        # create and start timer for all following updates
        self.timer = QtCore.QTimer()
        self.timer.timeout.connect(self.update_clock)
        self.timer.setInterval(60000)
        self.timer.start() 
Example #4
Source File: node.py    From BlueSTSDK_Python with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def characteristic_can_be_written(self, characteristic):
        """Check if a characteristics can be written.

        Args:
            characteristic (Characteristic): The BLE characteristic to check.
            Refer to
            `Characteristic <https://ianharvey.github.io/bluepy-doc/characteristic.html>`_
            for more information.

        Returns:
            bool: True if the characteristic can be written, False otherwise.
        """
        try:
            if characteristic is not None:
                with lock(self):
                    return "WRITE" in characteristic.propertiesToString()
            return False
        except BTLEException as e:
            self._unexpected_disconnect() 
Example #5
Source File: node.py    From BlueSTSDK_Python with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def characteristic_can_be_read(self, characteristic):
        """Check if a characteristics can be read.

        Args:
            characteristic (Characteristic): The BLE characteristic to check.
            Refer to
            `Characteristic <https://ianharvey.github.io/bluepy-doc/characteristic.html>`_
            for more information.

        Returns:
            bool: True if the characteristic can be read, False otherwise.
        """
        try:
            if characteristic is not None:
                with lock(self):
                    return "READ" in characteristic.propertiesToString()
            return False
        except BTLEException as e:
            self._unexpected_disconnect() 
Example #6
Source File: node.py    From BlueSTSDK_Python with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def update_advertising_data(self, advertising_data):
        """Update advertising data.

        Args:
            advertising_data (list): Advertising data. Refer to 'getScanData()'
            method of
            `ScanEntry <https://ianharvey.github.io/bluepy-doc/scanentry.html>`_
            class for more information.

        Raises:
            :exc:`blue_st_sdk.utils.blue_st_exceptions.BlueSTInvalidAdvertisingDataException`
            is raised if the advertising data is not well formed.
        """
        try:
            self._advertising_data = BlueSTAdvertisingDataParser.parse(
                advertising_data)
        except BlueSTInvalidAdvertisingDataException as e:
            raise e 
Example #7
Source File: feature_activity_recognition.py    From BlueSTSDK_Python with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def get_time(self, sample):
        """Getting the date and the time from a sample.

        Args:
            sample (:class:`blue_st_sdk.feature.Sample`): Sample data.

        Returns:
            :class:`datetime`: The date and the time of the recognized activity
            if the sample is valid, "None" otherwise.
            Refer to
            `datetime <https://docs.python.org/2/library/datetime.html>`_
            for more information.
        """
        if sample is not None:
            if sample._data:
                if sample._data[self.TIME_FIELD] is not None:
                    return sample._data[self.TIME_FIELD]
        return None 
Example #8
Source File: now.py    From pypyr-cli with Apache License 2.0 5 votes vote down vote up
def run_step(context):
    """pypyr step saves current local datetime to context.

    Args:
        context: pypyr.context.Context. Mandatory.
                 The following context key is optional:
                - nowIn. str. Datetime formatting expression. For full list of
                  possible expressions, check here:
                  https://docs.python.org/3.7/library/datetime.html#strftime-and-strptime-behavior

    All inputs support pypyr formatting expressions.

    This step creates now in context, containing a string representation of the
    timestamp. If input formatting not specified, defaults to ISO8601.

    Default is:
    YYYY-MM-DDTHH:MM:SS.ffffff, or, if microsecond is 0, YYYY-MM-DDTHH:MM:SS

    Returns:
        None. updates context arg.

    """
    logger.debug("started")

    format_expression = context.get('nowIn', None)

    if format_expression:
        formatted_expression = context.get_formatted_string(format_expression)
        context['now'] = datetime.now(tzlocal()).strftime(formatted_expression)
    else:
        context['now'] = datetime.now(tzlocal()).isoformat()

    logger.info("timestamp %s saved to context now", context['now'])
    logger.debug("done") 
Example #9
Source File: timezone.py    From python2017 with MIT License 5 votes vote down vote up
def is_aware(value):
    """
    Determines if a given datetime.datetime is aware.

    The concept is defined in Python's docs:
    http://docs.python.org/library/datetime.html#datetime.tzinfo

    Assuming value.tzinfo is either None or a proper datetime.tzinfo,
    value.utcoffset() implements the appropriate logic.
    """
    return value.utcoffset() is not None 
Example #10
Source File: nowutc.py    From pypyr-cli with Apache License 2.0 5 votes vote down vote up
def run_step(context):
    """pypyr step saves current utc datetime to context.

    Args:
        context: pypyr.context.Context. Mandatory.
                 The following context key is optional:
                - nowUtcIn. str. Datetime formatting expression. For full list
                  of possible expressions, check here:
                  https://docs.python.org/3.7/library/datetime.html#strftime-and-strptime-behavior

    All inputs support pypyr formatting expressions.

    This step creates now in context, containing a string representation of the
    timestamp. If input formatting not specified, defaults to ISO8601.

    Default is:
    YYYY-MM-DDTHH:MM:SS.ffffff+00:00, or, if microsecond is 0,
    YYYY-MM-DDTHH:MM:SS

    Returns:
        None. updates context arg.

    """
    logger.debug("started")

    format_expression = context.get('nowUtcIn', None)

    if format_expression:
        formatted_expression = context.get_formatted_string(format_expression)
        context['nowUtc'] = datetime.now(
            timezone.utc).strftime(formatted_expression)
    else:
        context['nowUtc'] = datetime.now(timezone.utc).isoformat()

    logger.info("timestamp %s saved to context nowUtc", context['nowUtc'])
    logger.debug("done") 
Example #11
Source File: feature.py    From BlueSTSDK_Python with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_last_update(self):
        """Get the time of the last update.

        Returns:
            datetime: The time of the last update received. Refer to
            `datetime <https://docs.python.org/2/library/datetime.html>`_
            for more information.
        """
        return self._last_update 
Example #12
Source File: feature.py    From BlueSTSDK_Python with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_characteristic(self):
        """Get the characteristic that offers the feature.

        Note:
            By design, it is the characteristic that offers more features beyond
            the current one, among those offering the current one.

        Returns:
            characteristic: The characteristic that offers the feature. Refer to
            `Characteristic <https://ianharvey.github.io/bluepy-doc/characteristic.html>`_
            for more information.
        """
        return self._characteristic 
Example #13
Source File: node.py    From BlueSTSDK_Python with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _build_features(self, characteristic):
        """Build the exported features of a BLE characteristic.

        After building the features, add them to the dictionary of the features
        to be updated.

        Args:
            characteristic (Characteristic): The BLE characteristic. Refer to
            `Characteristic <https://ianharvey.github.io/bluepy-doc/characteristic.html>`_
            for more information.
        """
        try:
            # Extracting the feature mask from the characteristic's UUID.
            feature_mask = FeatureCharacteristic.extract_feature_mask(
                characteristic.uuid)
            # Looking for the exported features in reverse order to get them in
            # the correct order in case of characteristic that exports multiple
            # features.
            features = []
            mask = 1 << 31
            for i in range(0, 32):
                if (feature_mask & mask) != 0:
                    if mask in self._mask_to_feature_dic:
                        feature = self._mask_to_feature_dic[mask]
                        if feature is not None:
                            feature.set_enable(True)
                            features.append(feature)
                mask = mask >> 1

            # If the features are valid, add an entry for the corresponding
            # characteristic.
            if features:
                with lock(self):
                    self._update_char_handle_to_features_dict[
                        characteristic.getHandle()] = features
        except BTLEException as e:
            self._node._unexpected_disconnect() 
Example #14
Source File: node.py    From BlueSTSDK_Python with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _build_features_known_uuid(self, characteristic, feature_classes):
        """Build the given features of a BLE characteristic.

        After building the features, add them to the dictionary of the features
        to be updated.

        Args:
            characteristic (Characteristic): The BLE characteristic. Refer to
            `Characteristic <https://ianharvey.github.io/bluepy-doc/characteristic.html>`_
            for more information.
            feature_classes (list): The list of feature-classes to instantiate.
        """
        # Build the features.
        features = []
        for feature_class in feature_classes:
            feature = self._build_feature_from_class(feature_class)
            if feature is not None:
                feature.set_enable(True)
                features.append(feature)
                self._available_features.append(feature)

        # If the features are valid, add an entry for the corresponding
        # characteristic.
        try:
            if features:
                with lock(self):
                    self._update_char_handle_to_features_dict[
                        characteristic.getHandle()] = features
        except BTLEException as e:
            self._unexpected_disconnect() 
Example #15
Source File: node.py    From BlueSTSDK_Python with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_last_rssi_update_date(self):
        """Get the time of the last RSSI update received.

        Returns:
            datetime: The time of the last RSSI update received. Refer to
            `datetime <https://docs.python.org/2/library/datetime.html>`_
            for more information.
        """
        return self._last_rssi_update 
Example #16
Source File: utils.py    From toot with GNU General Public License v3.0 5 votes vote down vote up
def parse_datetime(value):
    """Returns an aware datetime in local timezone"""

    # In Python < 3.7, `%z` does not match `Z` offset
    # https://docs.python.org/3.7/library/datetime.html#strftime-and-strptime-behavior
    if value.endswith("Z"):
        dttm = datetime.strptime(value, "%Y-%m-%dT%H:%M:%S.%fZ").replace(tzinfo=timezone.utc)
    else:
        dttm = datetime.strptime(value, "%Y-%m-%dT%H:%M:%S.%f%z")

    return dttm.astimezone() 
Example #17
Source File: transform.py    From integrations-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_time_elapsed(transformers, column_name, **modifiers):
    """
    Send the number of seconds elapsed from a time in the past as a `gauge`.

    For example, if the result is an instance of
    [datetime.datetime](https://docs.python.org/3/library/datetime.html#datetime.datetime) representing 5 seconds ago,
    then this would submit with a value of `5`.

    The optional modifier `format` indicates what format the result is in. By default it is `native`, assuming the
    underlying library provides timestamps as `datetime` objects. If it does not and passes them through directly as
    strings, you must provide the expected timestamp format using the
    [supported codes](https://docs.python.org/3/library/datetime.html#strftime-and-strptime-format-codes).

    !!! note
        The code `%z` (lower case) is not supported on Windows.
    """
    time_format = modifiers.pop('format', 'native')
    if not isinstance(time_format, str):
        raise ValueError('the `format` parameter must be a string')

    gauge = transformers['gauge'](transformers, column_name, **modifiers)

    if time_format == 'native':

        def time_elapsed(_, value, **kwargs):
            value = normalize_datetime(value)
            gauge(_, (datetime.now(value.tzinfo) - value).total_seconds(), **kwargs)

    else:

        def time_elapsed(_, value, **kwargs):
            value = normalize_datetime(datetime.strptime(value, time_format))
            gauge(_, (datetime.now(value.tzinfo) - value).total_seconds(), **kwargs)

    return time_elapsed 
Example #18
Source File: timezone.py    From python2017 with MIT License 5 votes vote down vote up
def is_naive(value):
    """
    Determines if a given datetime.datetime is naive.

    The concept is defined in Python's docs:
    http://docs.python.org/library/datetime.html#datetime.tzinfo

    Assuming value.tzinfo is either None or a proper datetime.tzinfo,
    value.utcoffset() implements the appropriate logic.
    """
    return value.utcoffset() is None 
Example #19
Source File: git_scraper.py    From probe-scraper with Mozilla Public License 2.0 5 votes vote down vote up
def utc_timestamp(d):
    # See https://docs.python.org/3/library/datetime.html#datetime.datetime.timestamp
    # for why we're calculating this UTC timestamp explicitly
    return (d - datetime(1970, 1, 1)) / timedelta(seconds=1) 
Example #20
Source File: timezone.py    From openhgsenti with Apache License 2.0 5 votes vote down vote up
def is_naive(value):
    """
    Determines if a given datetime.datetime is naive.

    The concept is defined in Python's docs:
    http://docs.python.org/library/datetime.html#datetime.tzinfo

    Assuming value.tzinfo is either None or a proper datetime.tzinfo,
    value.utcoffset() implements the appropriate logic.
    """
    return value.utcoffset() is None 
Example #21
Source File: timezone.py    From openhgsenti with Apache License 2.0 5 votes vote down vote up
def is_aware(value):
    """
    Determines if a given datetime.datetime is aware.

    The concept is defined in Python's docs:
    http://docs.python.org/library/datetime.html#datetime.tzinfo

    Assuming value.tzinfo is either None or a proper datetime.tzinfo,
    value.utcoffset() implements the appropriate logic.
    """
    return value.utcoffset() is not None 
Example #22
Source File: timezone.py    From luscan-devel with GNU General Public License v2.0 5 votes vote down vote up
def is_naive(value):
    """
    Determines if a given datetime.datetime is naive.

    The logic is described in Python's docs:
    http://docs.python.org/library/datetime.html#datetime.tzinfo
    """
    return value.tzinfo is None or value.tzinfo.utcoffset(value) is None 
Example #23
Source File: timezone.py    From luscan-devel with GNU General Public License v2.0 5 votes vote down vote up
def is_aware(value):
    """
    Determines if a given datetime.datetime is aware.

    The logic is described in Python's docs:
    http://docs.python.org/library/datetime.html#datetime.tzinfo
    """
    return value.tzinfo is not None and value.tzinfo.utcoffset(value) is not None 
Example #24
Source File: timezone.py    From python with Apache License 2.0 5 votes vote down vote up
def is_naive(value):
    """
    Determines if a given datetime.datetime is naive.

    The concept is defined in Python's docs:
    http://docs.python.org/library/datetime.html#datetime.tzinfo

    Assuming value.tzinfo is either None or a proper datetime.tzinfo,
    value.utcoffset() implements the appropriate logic.
    """
    return value.utcoffset() is None 
Example #25
Source File: timezone.py    From python with Apache License 2.0 5 votes vote down vote up
def is_aware(value):
    """
    Determines if a given datetime.datetime is aware.

    The concept is defined in Python's docs:
    http://docs.python.org/library/datetime.html#datetime.tzinfo

    Assuming value.tzinfo is either None or a proper datetime.tzinfo,
    value.utcoffset() implements the appropriate logic.
    """
    return value.utcoffset() is not None 
Example #26
Source File: timezone.py    From Hands-On-Application-Development-with-PyCharm with MIT License 5 votes vote down vote up
def is_naive(value):
    """
    Determine if a given datetime.datetime is naive.

    The concept is defined in Python's docs:
    https://docs.python.org/library/datetime.html#datetime.tzinfo

    Assuming value.tzinfo is either None or a proper datetime.tzinfo,
    value.utcoffset() implements the appropriate logic.
    """
    return value.utcoffset() is None 
Example #27
Source File: timezone.py    From Hands-On-Application-Development-with-PyCharm with MIT License 5 votes vote down vote up
def is_aware(value):
    """
    Determine if a given datetime.datetime is aware.

    The concept is defined in Python's docs:
    https://docs.python.org/library/datetime.html#datetime.tzinfo

    Assuming value.tzinfo is either None or a proper datetime.tzinfo,
    value.utcoffset() implements the appropriate logic.
    """
    return value.utcoffset() is not None 
Example #28
Source File: date.py    From mimesis with MIT License 5 votes vote down vote up
def bulk_create_datetimes(date_start: DateTime,
                              date_end: DateTime, **kwargs) -> List[DateTime]:
        """Bulk create datetime objects.

        This method creates list of datetime objects from
        ``date_start`` to ``date_end``.

        You can use the following keyword arguments:

        * ``days``
        * ``hours``
        * ``minutes``
        * ``seconds``
        * ``microseconds``

        See datetime module documentation for more:
        https://docs.python.org/3.7/library/datetime.html#timedelta-objects


        :param date_start: Begin of the range.
        :param date_end: End of the range.
        :param kwargs: Keyword arguments for datetime.timedelta
        :return: List of datetime objects
        :raises: ValueError: When ``date_start``/``date_end`` not passed and
            when ``date_start`` larger than ``date_end``.
        """
        dt_objects = []

        if not date_start and not date_end:
            raise ValueError('You must pass date_start and date_end')

        if date_end < date_start:
            raise ValueError('date_start can not be larger than date_end')

        while date_start <= date_end:
            date_start += timedelta(**kwargs)
            dt_objects.append(date_start)

        return dt_objects 
Example #29
Source File: serializer.py    From SQLAlchemy-serializer with MIT License 5 votes vote down vote up
def to_dict(self, only=(), rules=(),
                date_format=None, datetime_format=None, time_format=None, tzinfo=None,
                decimal_format=None, serialize_types=None):
        """
        Returns SQLAlchemy model's data in JSON compatible format

        For details about datetime formats follow:
        https://docs.python.org/3/library/datetime.html#strftime-and-strptime-behavior

        :param only: exclusive schema to replace default one (always have higher priority than rules)
        :param rules: schema to extend default one or schema defined in "only"
        :param date_format: str
        :param datetime_format: str
        :param time_format: str
        :param decimal_format: str
        :param tzinfo: datetime.tzinfo converts datetimes to local user timezone
        :return: data: dict
        """
        s = Serializer(
            date_format=date_format or self.date_format,
            datetime_format=datetime_format or self.datetime_format,
            time_format=time_format or self.time_format,
            decimal_format=decimal_format or self.decimal_format,
            tzinfo=tzinfo or self.get_tzinfo(),
            serialize_types=serialize_types or self.serialize_types
        )
        return s(self, only=only, extend=rules) 
Example #30
Source File: timezone.py    From bioforum with MIT License 5 votes vote down vote up
def is_naive(value):
    """
    Determine if a given datetime.datetime is naive.

    The concept is defined in Python's docs:
    http://docs.python.org/library/datetime.html#datetime.tzinfo

    Assuming value.tzinfo is either None or a proper datetime.tzinfo,
    value.utcoffset() implements the appropriate logic.
    """
    return value.utcoffset() is None