Add worldclock custom format (#36157)

This commit is contained in:
Indu Prakash 2020-06-25 13:41:53 -05:00 committed by GitHub
parent 4aedafc73a
commit 15773cb3e0
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 33 additions and 9 deletions

View file

@ -9,18 +9,19 @@ import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.entity import Entity
import homeassistant.util.dt as dt_util
CONF_TIME_FORMAT = "time_format"
_LOGGER = logging.getLogger(__name__)
DEFAULT_NAME = "Worldclock Sensor"
ICON = "mdi:clock"
TIME_STR_FORMAT = "%H:%M"
DEFAULT_TIME_STR_FORMAT = "%H:%M"
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
{
vol.Required(CONF_TIME_ZONE): cv.time_zone,
vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
vol.Optional(CONF_TIME_FORMAT, default=DEFAULT_TIME_STR_FORMAT): cv.string,
}
)
@ -30,17 +31,20 @@ async def async_setup_platform(hass, config, async_add_entities, discovery_info=
name = config.get(CONF_NAME)
time_zone = dt_util.get_time_zone(config.get(CONF_TIME_ZONE))
async_add_entities([WorldClockSensor(time_zone, name)], True)
async_add_entities(
[WorldClockSensor(time_zone, name, config.get(CONF_TIME_FORMAT),)], True,
)
class WorldClockSensor(Entity):
"""Representation of a World clock sensor."""
def __init__(self, time_zone, name):
def __init__(self, time_zone, name, time_format):
"""Initialize the sensor."""
self._name = name
self._time_zone = time_zone
self._state = None
self._time_format = time_format
@property
def name(self):
@ -59,4 +63,4 @@ class WorldClockSensor(Entity):
async def async_update(self):
"""Get the time and updates the states."""
self._state = dt_util.now(time_zone=self._time_zone).strftime(TIME_STR_FORMAT)
self._state = dt_util.now(time_zone=self._time_zone).strftime(self._time_format)

View file

@ -15,15 +15,35 @@ class TestWorldClockSensor(unittest.TestCase):
self.hass = get_test_home_assistant()
self.time_zone = dt_util.get_time_zone("America/New_York")
def test_time(self):
"""Test the time at a different location."""
config = {"sensor": {"platform": "worldclock", "time_zone": "America/New_York"}}
assert setup_component(self.hass, "sensor", config)
self.hass.block_till_done()
self.addCleanup(self.hass.stop)
def test_time(self):
"""Test the time at a different location."""
state = self.hass.states.get("sensor.worldclock_sensor")
assert state is not None
assert state.state == dt_util.now(time_zone=self.time_zone).strftime("%H:%M")
def test_time_format(self):
"""Test time_format setting."""
time_format = "%a, %b %d, %Y %I:%M %p"
config = {
"sensor": {
"platform": "worldclock",
"time_zone": "America/New_York",
"time_format": time_format,
}
}
assert setup_component(self.hass, "sensor", config)
self.hass.block_till_done()
self.addCleanup(self.hass.stop)
state = self.hass.states.get("sensor.worldclock_sensor")
assert state is not None
assert state.state == dt_util.now(time_zone=self.time_zone).strftime(
time_format
)