当前位置: 首页>>代码示例>>Python>>正文


Python dt.now方法代码示例

本文整理汇总了Python中homeassistant.util.dt.now方法的典型用法代码示例。如果您正苦于以下问题:Python dt.now方法的具体用法?Python dt.now怎么用?Python dt.now使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在homeassistant.util.dt的用法示例。


在下文中一共展示了dt.now方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: update

# 需要导入模块: from homeassistant.util import dt [as 别名]
# 或者: from homeassistant.util.dt import now [as 别名]
def update(self):
        import pychromecast
        # from cast/media_player.py but is missing cast_type
        # KNOWN_CHROMECAST_INFO_KEY = 'cast_known_chromecasts'
        # _LOGGER.info('KNOWN_CHROMECAST_INFO_KEY: %s', self.hass.data[KNOWN_CHROMECAST_INFO_KEY])

        self._chromecast_devices = pychromecast.get_chromecasts()
        _LOGGER.debug('Found chromecast devices: %s', self._chromecast_devices)
        chromecasts = []
        for cast in self._chromecast_devices:
            device = {
                'name': cast.name,
                'cast_type': cast.cast_type,
                'model_name': cast.model_name,
                'uuid': str(cast.uuid),
                'manufacturer': cast.device.manufacturer
            }
            chromecasts.append(device)
        self._attributes['devices_json'] = json.dumps(chromecasts, ensure_ascii=False)
        self._attributes['devices'] = chromecasts
        self._attributes['last_update'] = dt.now().isoformat('T')
        self._state = STATE_OK 
开发者ID:fondberg,项目名称:spotcast,代码行数:24,代码来源:sensor.py

示例2: next_change

# 需要导入模块: from homeassistant.util import dt [as 别名]
# 或者: from homeassistant.util.dt import now [as 别名]
def next_change(self):
        """Datetime when the next change to the state is."""
        # Always need to update next rising and next setting so state can be
        # determined.
        next_events = [self.next_rising, self.next_setting]
        # Only need to update remaining properties if they will be reported
        # in attributes.
        for attr in [STATE_ATTR_NEXT_DAWN,
                     STATE_ATTR_NEXT_DUSK,
                     STATE_ATTR_NEXT_MIDNIGHT,
                     STATE_ATTR_NEXT_NOON]:
            if attr in self._attrs:
                next_events.append(self._attrs[attr])
        # For sunrise, sunset, daylights and max_elevation, update at next
        # "real" midnight (as opposed to next_midnight, which is solar
        # midnight.) But subtract one second because point_in_time_listener()
        # will add one.
        if any(attr in self._attrs for attr in
               [STATE_ATTR_SUNRISE, STATE_ATTR_SUNSET,
                STATE_ATTR_DAYLIGHT, STATE_ATTR_PREV_DAYLIGHT,
                STATE_ATTR_NEXT_DAYLIGHT, STATE_ATTR_MAX_ELEVATION]):
            midnight = dt_util.start_of_local_day(
                dt_util.now() + timedelta(days=1))
            next_events.append(dt_util.as_utc(midnight) - timedelta(seconds=1))
        return min(next_events) 
开发者ID:pnbruckner,项目名称:homeassistant-config,代码行数:27,代码来源:__init__.py

示例3: async_added_to_hass

# 需要导入模块: from homeassistant.util import dt [as 别名]
# 或者: from homeassistant.util.dt import now [as 别名]
def async_added_to_hass(self):
        if self._using_wu:
            return

        @callback
        def sensor_state_listener(entity, old_state, new_state):
            if new_state and (not old_state or
                              new_state.state != old_state.state):
                self.async_schedule_update_ha_state(True)

        @callback
        def sensor_startup(event):
            self._init_complete = True

            # Update whenever source entity changes.
            async_track_state_change(
                self.hass, self._entity_id, sensor_state_listener)

            # Update now that source entity has had a chance to initialize.
            self.async_schedule_update_ha_state(True)

        self.hass.bus.async_listen_once(
            EVENT_HOMEASSISTANT_START, sensor_startup) 
开发者ID:pnbruckner,项目名称:homeassistant-config,代码行数:25,代码来源:sensor.py

示例4: should_poll

# 需要导入模块: from homeassistant.util import dt [as 别名]
# 或者: from homeassistant.util.dt import now [as 别名]
def should_poll(self):
        # For the system (i.e., EntityPlatform) to configure itself to
        # periodically call our async_update method any call to this method
        # during initializaton must return True. After that, for WU we'll
        # always poll, and for others we'll only need to poll during the ramp
        # up and down periods around sunrise and sunset, and then once more
        # when period is done to make sure ramping is completed.
        if not self._init_complete or self._using_wu:
            return True
        changing = 0 < self.sun_factor(dt_util.now()) < 1
        if changing:
            self._was_changing = True
            return True
        if self._was_changing:
            self._was_changing = False
            return True
        return False 
开发者ID:pnbruckner,项目名称:homeassistant-config,代码行数:19,代码来源:sensor.py

示例5: async_setup_platform

# 需要导入模块: from homeassistant.util import dt [as 别名]
# 或者: from homeassistant.util.dt import now [as 别名]
def async_setup_platform(hass, config, async_add_devices, discovery_info=None):
    """这个协程是程序的入口,其中add_devices函数也变成了异步版本."""
    _LOGGER.info("setup platform sensor.hachina...")

    city = config.get(CONF_CITY)
    appkey = config.get(CONF_APPKEY)

    data = WeatherData(hass, city, appkey)
    # 大家可以尝试把yield from去除,看看是什么效果(参见知识点小结)
    yield from data.async_update(dt_util.now())
    async_track_time_interval(hass, data.async_update, TIME_BETWEEN_UPDATES)

    # 根据配置文件options中的内容,添加若干个设备
    dev = []
    for option in config[CONF_OPTIONS]:
        dev.append(HAChinaWeatherSensor(data, option))
    async_add_devices(dev, True) 
开发者ID:zhujisheng,项目名称:HAComponent,代码行数:19,代码来源:hachina9.py

示例6: async_setup_platform

# 需要导入模块: from homeassistant.util import dt [as 别名]
# 或者: from homeassistant.util.dt import now [as 别名]
def async_setup_platform(hass, config, async_add_devices, discovery_info=None):
    """Set up the joke sensor."""

    key = config.get(CONF_KEY)
    name = config.get(CONF_NAME)

    dev = []
    data = JuheJokeData(hass, key)
    sensor = JuheJokeSensor(data, name)
    dev.append(sensor)

    async_add_devices(dev, True)

    def update(call=None):
        '''Update the data by service call'''
        data.update(dt_util.now())
        sensor.async_update()

    hass.services.async_register(DOMAIN, name+'_update',update) 
开发者ID:zhujisheng,项目名称:HAComponent,代码行数:21,代码来源:sensor.py

示例7: async_setup_platform

# 需要导入模块: from homeassistant.util import dt [as 别名]
# 或者: from homeassistant.util.dt import now [as 别名]
def async_setup_platform(hass, config, async_add_devices, discovery_info=None):

    _LOGGER.debug("starting platform setup")

    """get configuration params"""
    ip_address = config.get(CONF_IP_ADDRESS)
    mac = config.get(CONF_MAC).encode().replace(b':', b'')
    mac_addr = binascii.unhexlify(mac)
    timeout = config.get(CONF_TIMEOUT)

    """initiate connection to s1c hub"""
    conn_obj = HubConnection(ip_address, mac_addr, timeout)

    """discovering the sensors and initiating entities"""
    raw_data = conn_obj.get_initial_data()
    sensors = []
    for i, sensor in enumerate(raw_data["sensors"]):
        sensors.append(S1C_SENSOR(hass, sensor["name"], sensor["type"], conn_obj.parse_status(sensor["type"], str(sensor["status"])), now()))
    if sensors:
        async_add_devices(sensors, True)

    """starting the sensors status change watcher"""
    WatchSensors(hass, conn_obj).start()

    return True 
开发者ID:TomerFi,项目名称:home-assistant-custom-components,代码行数:27,代码来源:sensor.py

示例8: check_loop_run

# 需要导入模块: from homeassistant.util import dt [as 别名]
# 或者: from homeassistant.util.dt import now [as 别名]
def check_loop_run(self):
        """max exceptions allowed in loop before exiting"""
        max_exceptions_before_stop = 50
        """max minutes to remmember the last excption"""
        max_minutes_from_last_exception = 1
        
        current_dt = now()
        if not (self._last_exception_dt is None):
            if (self._last_exception_dt.year == current_dt.year and self._last_exception_dt.month == current_dt.month and self._last_exception_dt.day == current_dt.day):
                calc_dt = current_dt - self._last_exception_dt
                diff = divmod(calc_dt.days * 86400 + calc_dt.seconds, 60)
                if (diff[0] > max_minutes_from_last_exception):
                    self._exception_count = 0
                else:
                    self._exception_count += 1
            else:
                self._exception_count = 0
        else:
            self._exception_count = 0

        if not (max_exceptions_before_stop > self._exception_count):
            _LOGGER.error("max exceptions allowed in watch loop exceeded, stoping watch loop")
            self._ok_to_run = False

        self._last_exception_dt = current_dt 
开发者ID:TomerFi,项目名称:home-assistant-custom-components,代码行数:27,代码来源:sensor.py

示例9: async_setup

# 需要导入模块: from homeassistant.util import dt [as 别名]
# 或者: from homeassistant.util.dt import now [as 别名]
def async_setup(hass, config):
    """Track the state of the sun."""
    if config.get(CONF_ELEVATION) is not None:
        _LOGGER.warning(
            "Elevation is now configured in home assistant core. "
            "See https://home-assistant.io/docs/configuration/basic/")

    sun = Sun(hass, get_astral_location(hass), config[DOMAIN])
    sun.point_in_time_listener(dt_util.utcnow())

    return True 
开发者ID:pnbruckner,项目名称:homeassistant-config,代码行数:13,代码来源:__init__.py

示例10: point_in_time_listener

# 需要导入模块: from homeassistant.util import dt [as 别名]
# 或者: from homeassistant.util.dt import now [as 别名]
def point_in_time_listener(self, now):
        """Run when the state of the sun has changed."""
        if self._update_position:
            self.update_sun_position(now)
        self.update_as_of(now)
        self.async_schedule_update_ha_state()

        # Schedule next update at next_change+1 second so sun state has changed
        async_track_point_in_utc_time(
            self.hass, self.point_in_time_listener,
            self.next_change + timedelta(seconds=1)) 
开发者ID:pnbruckner,项目名称:homeassistant-config,代码行数:13,代码来源:__init__.py

示例11: __init__

# 需要导入模块: from homeassistant.util import dt [as 别名]
# 或者: from homeassistant.util.dt import now [as 别名]
def __init__(self, hass, city, appkey):
        """初始化函数."""
        self._url = "https://way.jd.com/he/freeweather"
        self._params = {"city": city,
                        "appkey": appkey}
        self._temprature = None
        self._humidity = None
        self._pm25 = None
        self._updatetime = None

        self.update(dt_util.now())
        # 每隔TIME_BETWEEN_UPDATES,调用一次update(),从京东万象获取数据
        track_time_interval(hass, self.update, TIME_BETWEEN_UPDATES) 
开发者ID:zhujisheng,项目名称:HAComponent,代码行数:15,代码来源:hachina8.py

示例12: update

# 需要导入模块: from homeassistant.util import dt [as 别名]
# 或者: from homeassistant.util.dt import now [as 别名]
def update(self, now):
        """从远程更新信息."""
        _LOGGER.info("Update from JingdongWangxiang's OpenAPI...")

        # 通过HTTP访问,获取需要的信息
        infomation_file = request.urlopen(
            self._url, parse.urlencode(self._params).encode('utf-8'))

        content = infomation_file.read()
        result = json.loads(content.decode('utf-8'))

        if result is None:
            _LOGGER.error("Request api Error")
            return
        elif result["code"] != "10000":
            _LOGGER.error("Error API return, code=%s, msg=%s",
                          result["code"],
                          result["msg"])
            return

        # 根据http返回的结果,更新数据
        all_result = result["result"]["HeWeather5"][0]
        self._temprature = all_result["now"]["tmp"]
        self._humidity = all_result["now"]["hum"]
        self._pm25 = all_result["aqi"]["city"]["pm25"]
        self._updatetime = all_result["basic"]["update"]["loc"] 
开发者ID:zhujisheng,项目名称:HAComponent,代码行数:28,代码来源:hachina8.py

示例13: update

# 需要导入模块: from homeassistant.util import dt [as 别名]
# 或者: from homeassistant.util.dt import now [as 别名]
def update(self, now):
        """Get the latest data and updates the states."""

        params = {
            "key": self.key,
            "page": randint(1,25000),
            "pagesize": 20
            }

        f = request.urlopen( self.url, parse.urlencode(params).encode('utf-8') )

        content = f.read()
        
        result = json.loads(content.decode('utf-8'))

        if result is None:
            _LOGGER.error("Request api Error")
            return
        elif (result["error_code"] != 0):
            _LOGGER.error("Error API return, errorcode=%s, reson=%s",
                          result["error_code"],
                          result["reason"],
                          )
            return
        
        self.story = {}
        i = 0
        for data in result["result"]["data"]:
            i = i+1
            self.story["story%d" %(i)] = data["content"]
            
        self.state = 'ready' 
开发者ID:zhujisheng,项目名称:HAComponent,代码行数:34,代码来源:sensor.py

示例14: async_setup_platform

# 需要导入模块: from homeassistant.util import dt [as 别名]
# 或者: from homeassistant.util.dt import now [as 别名]
def async_setup_platform(hass, config, async_add_devices, discovery_info=None):

    api_key = config.get(CONF_API_KEY)
    origin = config.get(CONF_ORIGIN)
    destination = config.get(CONF_DESTINATION)
    travel_mode = config.get(CONF_TRAVEL_MODE)
    strategy = config.get(CONF_STRATEGY)

    name = config.get(CONF_NAME)
    friendly_name = config.get(CONF_FRIENDLY_NAME)

    data = GaodeTravelTimeData( hass, api_key, origin, destination, travel_mode, strategy )



    if(yield from data.async_setup()):
        yield from data.async_update(dt_util.now())
        async_track_time_interval( hass, data.async_update, TIME_BETWEEN_UPDATES )

        sensor = GaodeTravelTimeSensor( hass, name, friendly_name, data )
        async_add_devices([sensor])
        
        @asyncio.coroutine
        def async_update(call=None):
            '''Update the data by service call'''
            yield from data.async_update(dt_util.now())
            sensor.async_update()
        
        hass.services.async_register(DOMAIN, name+'_update', async_update) 
开发者ID:zhujisheng,项目名称:HAComponent,代码行数:31,代码来源:sensor.py

示例15: async_setup_platform

# 需要导入模块: from homeassistant.util import dt [as 别名]
# 或者: from homeassistant.util.dt import now [as 别名]
def async_setup_platform(hass, config, async_add_devices, discovery_info=None):
    """Set up the laohuangli sensor."""

    key = config.get(CONF_KEY)

    data = JuheLaohuangliData(hass, key)
    yield from data.async_update(dt_util.now())
    async_track_time_change( hass, data.async_update, hour=[0], minute=[0], second=[1] )

    dev = []
    dev.append(JuheLaohuangliSensor(data))
    async_add_devices(dev, True) 
开发者ID:zhujisheng,项目名称:HAComponent,代码行数:14,代码来源:sensor.py


注:本文中的homeassistant.util.dt.now方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。