Exemplo n.º 1
0
    def handle_new_task(call):
        """Called when a user creates a new Todoist Task from HASS."""
        project_name = call.data[PROJECT_NAME]
        project_id = project_id_lookup[project_name]

        # Create the task
        item = api.items.add(call.data[CONTENT], project_id)

        if LABELS in call.data:
            task_labels = call.data[LABELS]
            label_ids = [
                label_id_lookup[label.lower()] for label in task_labels
            ]
            item.update(labels=label_ids)

        if PRIORITY in call.data:
            item.update(priority=call.data[PRIORITY])

        if DUE_DATE in call.data:
            due_date = dt.parse_datetime(call.data[DUE_DATE])
            if due_date is None:
                due = dt.parse_date(call.data[DUE_DATE])
                due_date = datetime(due.year, due.month, due.day)
            # Format it in the manner Todoist expects
            due_date = dt.as_utc(due_date)
            date_format = '%Y-%m-%dT%H:%M'
            due_date = datetime.strftime(due_date, date_format)
            item.update(due_date_utc=due_date)
        # Commit changes
        api.commit()
        _LOGGER.debug("Created Todoist task: %s", call.data[CONTENT])
Exemplo n.º 2
0
    async def async_added_to_hass(self):
        """Run when entity about to be added."""
        await super().async_added_to_hass()

        # Priority 1: Initial value
        if self.state is not None:
            return

        # Priority 2: Old state
        old_state = await self.async_get_last_state()
        if old_state is None:
            self._current_datetime = dt_util.parse_datetime(DEFAULT_VALUE)
            return

        if self.has_date and self.has_time:
            date_time = dt_util.parse_datetime(old_state.state)
            if date_time is None:
                self._current_datetime = dt_util.parse_datetime(DEFAULT_VALUE)
                return
            self._current_datetime = date_time
        elif self.has_date:
            date = dt_util.parse_date(old_state.state)
            if date is None:
                self._current_datetime = dt_util.parse_datetime(DEFAULT_VALUE)
                return
            self._current_datetime = datetime.datetime.combine(
                date, DEFAULT_TIME)
        else:
            time = dt_util.parse_time(old_state.state)
            if time is None:
                self._current_datetime = dt_util.parse_datetime(DEFAULT_VALUE)
                return
            self._current_datetime = datetime.datetime.combine(
                DEFAULT_DATE, time)
Exemplo n.º 3
0
    def __init__(self, config: dict) -> None:
        """Initialize a select input."""
        self._config = config
        self.editable = True
        self._current_datetime = None

        initial = config.get(CONF_INITIAL)
        if not initial:
            return

        if self.has_date and self.has_time:
            current_datetime = dt_util.parse_datetime(initial)

        elif self.has_date:
            date = dt_util.parse_date(initial)
            current_datetime = py_datetime.datetime.combine(date, DEFAULT_TIME)

        else:
            time = dt_util.parse_time(initial)
            current_datetime = py_datetime.datetime.combine(
                py_datetime.date.today(), time
            )

        # If the user passed in an initial value with a timezone, convert it to right tz
        if current_datetime.tzinfo is not None:
            self._current_datetime = current_datetime.astimezone(
                dt_util.DEFAULT_TIME_ZONE
            )
        else:
            self._current_datetime = current_datetime.replace(
                tzinfo=dt_util.DEFAULT_TIME_ZONE
            )
Exemplo n.º 4
0
    def handle_new_task(call):
        """Call when a user creates a new Todoist Task from HASS."""
        project_name = call.data[PROJECT_NAME]
        project_id = project_id_lookup[project_name]

        # Create the task
        item = api.items.add(call.data[CONTENT], project_id)

        if LABELS in call.data:
            task_labels = call.data[LABELS]
            label_ids = [
                label_id_lookup[label.lower()]
                for label in task_labels]
            item.update(labels=label_ids)

        if PRIORITY in call.data:
            item.update(priority=call.data[PRIORITY])

        if DUE_DATE in call.data:
            due_date = dt.parse_datetime(call.data[DUE_DATE])
            if due_date is None:
                due = dt.parse_date(call.data[DUE_DATE])
                due_date = datetime(due.year, due.month, due.day)
            # Format it in the manner Todoist expects
            due_date = dt.as_utc(due_date)
            date_format = '%Y-%m-%dT%H:%M'
            due_date = datetime.strftime(due_date, date_format)
            item.update(due_date_utc=due_date)
        # Commit changes
        api.commit()
        _LOGGER.debug("Created Todoist task: %s", call.data[CONTENT])
Exemplo n.º 5
0
 def _get_date(date):
     """Get the dateTime from date or dateTime as a local."""
     if 'date' in date:
         return dt.as_utc(dt.dt.datetime.combine(
             dt.parse_date(date['date']), dt.dt.time()))
     else:
         return dt.parse_datetime(date['dateTime'])
Exemplo n.º 6
0
 def _get_date(date):
     """Get the dateTime from date or dateTime as a local."""
     if 'date' in date:
         return dt.start_of_local_day(dt.dt.datetime.combine(
             dt.parse_date(date['date']), dt.dt.time.min))
     else:
         return dt.as_local(dt.parse_datetime(date['dateTime']))
Exemplo n.º 7
0
def get_date(date):
    """Get the dateTime from date or dateTime as a local."""
    if "date" in date:
        return dt.start_of_local_day(
            dt.dt.datetime.combine(dt.parse_date(date["date"]),
                                   dt.dt.time.min))
    return dt.as_local(dt.parse_datetime(date["dateTime"]))
Exemplo n.º 8
0
    async def async_added_to_hass(self):
        """Run when entity about to be added."""
        await super().async_added_to_hass()
        restore_val = None

        # Priority 1: Initial State
        if self._initial is not None:
            restore_val = self._initial

        # Priority 2: Old state
        if restore_val is None:
            old_state = await self.async_get_last_state()
            if old_state is not None:
                restore_val = old_state.state

        if not self.has_date:
            if not restore_val:
                restore_val = DEFAULT_VALUE.split()[1]
            self._current_datetime = dt_util.parse_time(restore_val)
        elif not self.has_time:
            if not restore_val:
                restore_val = DEFAULT_VALUE.split()[0]
            self._current_datetime = dt_util.parse_date(restore_val)
        else:
            if not restore_val:
                restore_val = DEFAULT_VALUE
            self._current_datetime = dt_util.parse_datetime(restore_val)
Exemplo n.º 9
0
async def async_setup_platform(hass,
                               config,
                               async_add_entities,
                               discovery_info=None):
    """Set up the Anniversary sensor."""
    if hass.config.time_zone is None:
        _LOGGER.error("Timezone is not set in Home Assistant configuration")
        return False

    sensors = []

    for device, device_config in config[CONF_SENSORS].items():
        date_str = device_config.get(ATTR_DATE)
        is_lunar = device_config.get(CONF_IS_LUNAR_DATE)
        is_intercalation = device_config.get(CONF_INTERCALATION)
        anniv_type = device_config.get(CONF_TYPE)

        name = device_config.get(CONF_NAME)
        if name == '':
            name = device

        is_mmdd = False
        if dt_util.parse_date(date_str) is None:
            year_added_date_str = str(
                dt_util.as_local(
                    dt_util.utcnow()).date().year) + "-" + date_str
            if dt_util.parse_date(year_added_date_str) is not None:
                date_str = year_added_date_str
                is_mmdd = True
            else:
                continue

        sensor = AnniversarySensor(hass, device, name, date_str, is_lunar,
                                   is_intercalation, anniv_type, is_mmdd)
        async_track_point_in_utc_time(hass, sensor.point_in_time_listener,
                                      sensor.get_next_interval())

        sensors.append(sensor)

    sensor = AnniversaryTTSSensor(hass, "anniversary_tts",
                                  config.get(CONF_TTS_DAYS),
                                  config.get(CONF_TTS_SCAN_INTERVAL))
    async_track_point_in_utc_time(hass, sensor.point_in_time_listener,
                                  sensor.get_next_interval())
    sensors.append(sensor)

    async_add_entities(sensors, True)
Exemplo n.º 10
0
 def _get_date(date):
     """Get the dateTime from date or dateTime as a local."""
     if 'date' in date:
         return dt.start_of_local_day(
             dt.dt.datetime.combine(dt.parse_date(date['date']),
                                    dt.dt.time.min))
     else:
         return dt.as_local(dt.parse_datetime(date['dateTime']))
Exemplo n.º 11
0
        def to_python(self, value):
            """Validate and convert date."""
            parsed = dt_util.parse_date(value)

            if parsed is None:
                raise ValidationError()

            return parsed
Exemplo n.º 12
0
        def to_python(self, value):
            """Validate and convert date."""
            parsed = dt_util.parse_date(value)

            if parsed is None:
                raise ValidationError()

            return parsed
Exemplo n.º 13
0
 def _get_date(date):
     """Get the dateTime from date or dateTime as a local."""
     if 'date' in date:
         return dt.as_utc(
             dt.dt.datetime.combine(dt.parse_date(date['date']),
                                    dt.dt.time()))
     else:
         return dt.parse_datetime(date['dateTime'])
Exemplo n.º 14
0
def validate_date(value: str) -> str:
    """Input must be either none or a valid date."""
    if value is None:
        return None
    date = dt_util.parse_date(value)
    if date is None:
        raise vol.Invalid("Invalid date entered: {}".format(value))
    else:
        return date.strftime("%Y-%m-%d")
Exemplo n.º 15
0
def get_date(date: dict[str, Any]) -> datetime.datetime:
    """Get the dateTime from date or dateTime as a local."""
    if "date" in date:
        parsed_date = dt.parse_date(date["date"])
        assert parsed_date
        return dt.start_of_local_day(
            datetime.datetime.combine(parsed_date, datetime.time.min))
    parsed_datetime = dt.parse_datetime(date["dateTime"])
    assert parsed_datetime
    return dt.as_local(parsed_datetime)
Exemplo n.º 16
0
 def lunar_gapja(self, lunarDate):
     intercalation = False
     if '윤달' in lunarDate:
         intercalation = True
         lunarDate = lunarDate.replace(INTERCALATION, '')
     lunar = dt_util.parse_date(lunarDate)
     calendar = KoreanLunarCalendar()
     calendar.setLunarDate(lunar.year, lunar.month, lunar.day,
                           intercalation)
     return calendar.getGapJaString()
Exemplo n.º 17
0
    def update(self):
        """Update the data for the pickup."""
        from pyden.exceptions import HTTPError

        try:
            next_date = parse_date(self._client.next_pickup(self._pickup_type))
            self.humanized_pickup = self._humanize_pickup(next_date)
            self.raw_date = next_date.strftime('%B %e, %Y')
        except HTTPError as exc:
            _LOGGER.error('Unable to get next %s pickup date: %s',
                          self._pickup_type, exc)
Exemplo n.º 18
0
 def _update(self):
     """Update device state."""
     import fedexdeliverymanager
     status_counts = defaultdict(int)
     for package in fedexdeliverymanager.get_packages(self._session):
         status = slugify(package['primary_status'])
         skip = status == STATUS_DELIVERED and \
             parse_date(package['delivery_date']) < now().date()
         if skip:
             continue
         status_counts[status] += 1
     self._attributes = {ATTR_ATTRIBUTION: fedexdeliverymanager.ATTRIBUTION}
     self._attributes.update(status_counts)
     self._state = sum(status_counts.values())
Exemplo n.º 19
0
def date(value) -> date_sys:
    """Validate and transform a date."""
    if isinstance(value, date_sys):
        return value

    try:
        date_val = dt_util.parse_date(value)
    except TypeError:
        raise vol.Invalid('Not a parseable type')

    if date_val is None:
        raise vol.Invalid("Could not parse date")

    return date_val
def date(value: Any) -> date_sys:
    """Validate and transform a date."""
    if isinstance(value, date_sys):
        return value

    try:
        date_val = dt_util.parse_date(value)
    except TypeError as err:
        raise vol.Invalid("Not a parseable type") from err

    if date_val is None:
        raise vol.Invalid("Could not parse date")

    return date_val
 def to_datetime(obj):
     """To datetime."""
     if isinstance(obj, datetime):
         date_obj = (obj.replace(
             tzinfo=dt.DEFAULT_TIME_ZONE) if obj.tzinfo is None else obj)
     elif isinstance(obj, date):
         date_obj = dt.start_of_local_day(
             dt.dt.datetime.combine(obj, dt.dt.time.min))
     elif "date" in obj:
         date_obj = dt.start_of_local_day(
             dt.dt.datetime.combine(dt.parse_date(obj["date"]),
                                    dt.dt.time.min))
     else:
         date_obj = dt.as_local(dt.parse_datetime(obj["dateTime"]))
     return dt.as_utc(date_obj)
Exemplo n.º 22
0
 def __init__(self, hass, deviceId, name, dateStr, lunar, intercalation,
              aType, mmdd):
     """Initialize the sensor."""
     self.entity_id = async_generate_entity_id(ENTITY_ID_FORMAT,
                                               deviceId,
                                               hass=hass)
     self._name = name
     self._date = dt_util.parse_date(dateStr)
     self._lunar = lunar
     self._intercalation = intercalation
     self._type = aType
     self._mmdd = mmdd
     self._state = None
     self.hass = hass
     self._update_internal_state(dt_util.utcnow())
Exemplo n.º 23
0
 def lunar_to_solar(self, today, thisYear):
     lunarDate = self._date
     calendar = KoreanLunarCalendar()
     if thisYear or self._mmdd:
         calendar.setLunarDate(today.year, lunarDate.month, lunarDate.day,
                               self._intercalation)
         if calendar.SolarIsoFormat() == '0000-00-00':
             lunarDate2 = lunarDate - timedelta(1)
             calendar.setLunarDate(today.year, lunarDate2.month,
                                   lunarDate2.day, self._intercalation)
             _LOGGER.warn("Non-existent date correction : %s -> %s",
                          lunarDate, calendar.SolarIsoFormat())
     else:
         calendar.setLunarDate(lunarDate.year, lunarDate.month,
                               lunarDate.day, self._intercalation)
     return dt_util.parse_date(calendar.SolarIsoFormat())
Exemplo n.º 24
0
 def _update(self):
     """Update device state."""
     import fedexdeliverymanager
     status_counts = defaultdict(int)
     for package in fedexdeliverymanager.get_packages(self._session):
         status = slugify(package['primary_status'])
         skip = status == STATUS_DELIVERED and \
             parse_date(package['delivery_date']) < now().date()
         if skip:
             continue
         status_counts[status] += 1
     self._attributes = {
         ATTR_ATTRIBUTION: fedexdeliverymanager.ATTRIBUTION
     }
     self._attributes.update(status_counts)
     self._state = sum(status_counts.values())
Exemplo n.º 25
0
 def __init__(self, config: typing.Dict) -> None:
     """Initialize a select input."""
     self._config = config
     self.editable = True
     self._current_datetime = None
     initial = config.get(CONF_INITIAL)
     if initial:
         if self.has_date and self.has_time:
             self._current_datetime = dt_util.parse_datetime(initial)
         elif self.has_date:
             date = dt_util.parse_date(initial)
             self._current_datetime = datetime.datetime.combine(
                 date, DEFAULT_TIME)
         else:
             time = dt_util.parse_time(initial)
             self._current_datetime = datetime.datetime.combine(
                 DEFAULT_DATE, time)
Exemplo n.º 26
0
 def lunar_gapja(self, lunarDate):
     intercalation = False
     if '윤달' in lunarDate:
         intercalation = True
         lunarDate = lunarDate.replace(INTERCALATION, '')
     calendar = KoreanLunarCalendar()
     try:
         lunar = dt_util.parse_date(lunarDate)
         calendar.setLunarDate(lunar.year, lunar.month, lunar.day,
                               intercalation)
     except AttributeError:
         try:
             calendar.setLunarDate(lunarDate[:4], lunarDate[5:7],
                                   lunarDate[8:], intercalation)
         except:
             return "-"
     return calendar.getGapJaString()
Exemplo n.º 27
0
    def _update(self):
        """Update device state."""
        import upsmychoice
        status_counts = defaultdict(int)
        try:
            for package in upsmychoice.get_packages(self._session):
                status = slugify(package['status'])
                skip = status == STATUS_DELIVERED and \
                    parse_date(package['delivery_date']) < now().date()
                if skip:
                    continue
                status_counts[status] += 1
        except upsmychoice.UPSError:
            _LOGGER.error('Could not connect to UPS My Choice account')

        self._attributes = {ATTR_ATTRIBUTION: upsmychoice.ATTRIBUTION}
        self._attributes.update(status_counts)
        self._state = sum(status_counts.values())
Exemplo n.º 28
0
    async def async_added_to_hass(self):
        """Run when entity about to be added."""
        await super().async_added_to_hass()

        # Priority 1: Initial value
        if self.state is not None:
            return

        default_value = py_datetime.datetime.today().strftime(
            "%Y-%m-%d 00:00:00")

        # Priority 2: Old state
        old_state = await self.async_get_last_state()
        if old_state is None:
            self._current_datetime = dt_util.parse_datetime(default_value)
            return

        if self.has_date and self.has_time:
            date_time = dt_util.parse_datetime(old_state.state)
            if date_time is None:
                current_datetime = dt_util.parse_datetime(default_value)
            else:
                current_datetime = date_time

        elif self.has_date:
            date = dt_util.parse_date(old_state.state)
            if date is None:
                current_datetime = dt_util.parse_datetime(default_value)
            else:
                current_datetime = py_datetime.datetime.combine(
                    date, DEFAULT_TIME)

        else:
            time = dt_util.parse_time(old_state.state)
            if time is None:
                current_datetime = dt_util.parse_datetime(default_value)
            else:
                current_datetime = py_datetime.datetime.combine(
                    py_datetime.date.today(), time)

        self._current_datetime = current_datetime.replace(
            tzinfo=dt_util.DEFAULT_TIME_ZONE)
Exemplo n.º 29
0
    def _update(self):
        """Update device state."""
        import upsmychoice
        status_counts = defaultdict(int)
        try:
            for package in upsmychoice.get_packages(self._session):
                status = slugify(package['status'])
                skip = status == STATUS_DELIVERED and \
                    parse_date(package['delivery_date']) < now().date()
                if skip:
                    continue
                status_counts[status] += 1
        except upsmychoice.UPSError:
            _LOGGER.error('Could not connect to UPS My Choice account')

        self._attributes = {
            ATTR_ATTRIBUTION: upsmychoice.ATTRIBUTION
        }
        self._attributes.update(status_counts)
        self._state = sum(status_counts.values())
Exemplo n.º 30
0
    async def async_added_to_hass(self):
        """Run when entity about to be added."""
        restore_val = None

        # Priority 1: Initial State
        if self._initial is not None:
            restore_val = self._initial

        # Priority 2: Old state
        if restore_val is None:
            old_state = await async_get_last_state(self.hass, self.entity_id)
            if old_state is not None:
                restore_val = old_state.state

        if restore_val is not None:
            if not self.has_date:
                self._current_datetime = dt_util.parse_time(restore_val)
            elif not self.has_time:
                self._current_datetime = dt_util.parse_date(restore_val)
            else:
                self._current_datetime = dt_util.parse_datetime(restore_val)
Exemplo n.º 31
0
    async def async_added_to_hass(self):
        """Run when entity about to be added."""
        restore_val = None

        # Priority 1: Initial State
        if self._initial is not None:
            restore_val = self._initial

        # Priority 2: Old state
        if restore_val is None:
            old_state = await async_get_last_state(self.hass, self.entity_id)
            if old_state is not None:
                restore_val = old_state.state

        if restore_val is not None:
            if not self.has_date:
                self._current_datetime = dt_util.parse_time(restore_val)
            elif not self.has_time:
                self._current_datetime = dt_util.parse_date(restore_val)
            else:
                self._current_datetime = dt_util.parse_datetime(restore_val)
Exemplo n.º 32
0
def _handle_get_logbook(handler, path_match, data):
    """Return logbook entries."""
    date_str = path_match.group('date')

    if date_str:
        start_date = dt_util.parse_date(date_str)

        if start_date is None:
            handler.write_json_message("Error parsing JSON", HTTP_BAD_REQUEST)
            return

        start_day = dt_util.start_of_local_day(start_date)
    else:
        start_day = dt_util.start_of_local_day()

    end_day = start_day + timedelta(days=1)

    events = recorder.query_events(
        QUERY_EVENTS_BETWEEN,
        (dt_util.as_utc(start_day), dt_util.as_utc(end_day)))

    handler.write_json(humanify(events))
Exemplo n.º 33
0
def _handle_get_logbook(handler, path_match, data):
    """Return logbook entries."""
    date_str = path_match.group('date')

    if date_str:
        start_date = dt_util.parse_date(date_str)

        if start_date is None:
            handler.write_json_message("Error parsing JSON", HTTP_BAD_REQUEST)
            return

        start_day = dt_util.start_of_local_day(start_date)
    else:
        start_day = dt_util.start_of_local_day()

    end_day = start_day + timedelta(days=1)

    events = recorder.query_events(
        QUERY_EVENTS_BETWEEN,
        (dt_util.as_utc(start_day), dt_util.as_utc(end_day)))

    handler.write_json(humanify(events))
Exemplo n.º 34
0
def valid_initial(conf):
    """Check the initial value is valid."""
    initial = conf.get(CONF_INITIAL)
    if not initial:
        return conf

    if conf[CONF_HAS_DATE] and conf[CONF_HAS_TIME]:
        parsed_value = dt_util.parse_datetime(initial)
        if parsed_value is not None:
            return conf
        raise vol.Invalid(f"Initial value '{initial}' can't be parsed as a datetime")

    if conf[CONF_HAS_DATE]:
        parsed_value = dt_util.parse_date(initial)
        if parsed_value is not None:
            return conf
        raise vol.Invalid(f"Initial value '{initial}' can't be parsed as a date")

    parsed_value = dt_util.parse_time(initial)
    if parsed_value is not None:
        return conf
    raise vol.Invalid(f"Initial value '{initial}' can't be parsed as a time")
Exemplo n.º 35
0
def _api_history_period(handler, path_match, data):
    """Return history over a period of time."""
    date_str = path_match.group('date')
    one_day = timedelta(seconds=86400)

    if date_str:
        start_date = dt_util.parse_date(date_str)

        if start_date is None:
            handler.write_json_message("Error parsing JSON", HTTP_BAD_REQUEST)
            return

        start_time = dt_util.as_utc(dt_util.start_of_local_day(start_date))
    else:
        start_time = dt_util.utcnow() - one_day

    end_time = start_time + one_day

    entity_id = data.get('filter_entity_id')

    handler.write_json(
        get_significant_states(start_time, end_time, entity_id).values())
Exemplo n.º 36
0
    def from_dict(cls, restored: dict[str,
                                      Any]) -> SensorExtraStoredData | None:
        """Initialize a stored sensor state from a dict."""
        try:
            native_value = restored["native_value"]
            native_unit_of_measurement = restored["native_unit_of_measurement"]
        except KeyError:
            return None
        try:
            type_ = native_value["__type"]
            if type_ == "<class 'datetime.datetime'>":
                native_value = dt_util.parse_datetime(
                    native_value["isoformat"])
            elif type_ == "<class 'datetime.date'>":
                native_value = dt_util.parse_date(native_value["isoformat"])
        except TypeError:
            # native_value is not a dict
            pass
        except KeyError:
            # native_value is a dict, but does not have all values
            return None

        return cls(native_value, native_unit_of_measurement)
Exemplo n.º 37
0
def days_until_date(date_string: str, ts: datetime.datetime):
    date = dt_util.parse_date(date_string)
    diff = date - ts.date()
    return diff.days
Exemplo n.º 38
0
 def expiration_date(self):
     """Return the subscription expiration as a UTC datetime object."""
     return datetime.combine(
         dt_util.parse_date(self.claims['custom:sub-exp']),
         datetime.min.time()).replace(tzinfo=dt_util.UTC)
Exemplo n.º 39
0
 def expiration_date(self):
     """Return the subscription expiration as a UTC datetime object."""
     return datetime.combine(
         dt_util.parse_date(self.claims['custom:sub-exp']),
         datetime.min.time()).replace(tzinfo=dt_util.UTC)
Exemplo n.º 40
0
    def _update_internal_state(self, time_date):

        shopping_list = load_json(self.hass.config.path(PERSISTENCE),
                                  default=[])

        todo_list = {}
        tts_add_list = {}

        keys = {}

        def rename(todo_name):
            if todo_name in keys:
                keys[todo_name] += 1
                return ''.join([todo_name, '(', str(keys[todo_name]), ')'])
            else:
                keys[todo_name] = 1
                return todo_name

        for item in shopping_list:
            if not item['complete']:
                if item['name'].startswith('양') or item['name'].startswith(
                        '음'):
                    isLunar = item['name'].startswith('음')

                    try:
                        todo_date = item['name'][1:5]
                        todo_name = item['name'][6:]
                        solar_date = ''
                        ldate = ''
                        intercal = False

                        adddate = dt_util.parse_date(
                            str(datetime.now().year) + '-' + todo_date[0:2] +
                            '-' + todo_date[2:])

                        if isLunar:
                            intercal = '(윤)' in todo_name
                            solar_date = self.lunar_to_solar(adddate, intercal)
                            ldate = str(adddate.month) + "." + str(adddate.day)
                            if intercal:
                                ldate = ldate + INTERCALATION
                                todo_name = todo_name.replace('(윤)', '')
                        else:
                            solar_date = adddate

                        if solar_date < datetime.now().date():
                            solar_date = dt_util.parse_date(
                                str(datetime.now().year + 1) + '-' +
                                todo_date[0:2] + '-' + todo_date[2:])
                            if isLunar:
                                solar_date = self.lunar_to_solar(
                                    solar_date, intercal)

                        dday = (solar_date - datetime.now().date()).days
                        sdate = str(solar_date.month) + "." + str(
                            solar_date.day)

                        todo_rename = rename(todo_name)

                        if dday < self._tts_days + 1:
                            tts_add_list[todo_rename] = dday

                        if isLunar:
                            todo_list[todo_rename] = [
                                dday, sdate, ldate, todo_name
                            ]
                        else:
                            todo_list[todo_rename] = [
                                dday, sdate, "solar", todo_name
                            ]

                    except:
                        _LOGGER.warn("Not date : %s", item['name'])
                        pass

        self._attribute = todo_list

        tts_add_list.update(TTS)

        anniv_list = sorted(tts_add_list.items(), key=(lambda x: x[1]))
        msg = ''
        for anniv in anniv_list:
            name = anniv[0]
            value = anniv[1]
            if value < self._tts_days + 1:
                if todo_list.get(name) is not None:
                    name = todo_list.get(name)[3]
                if msg != '':
                    msg = msg + ", "
                if value == 0:
                    msg = msg + " ".join(["오늘은", name])
                elif value == 1:
                    msg = msg + " ".join(["내일은", name])
                else:
                    msg = msg + " ".join([str(value) + "일 후는", name])
        self._state = msg