Help needed with sensor strftime templating

I do try to convert a raw date/time value into a strftime format in a sensor template.
see below.

I’m not able to find the right format for this template. It is giving an error now
What is the right format for “value_template”?

clean_start:
      value_template: '{{ states("sensor.roborock_vacuum_s5e_last_clean_start").strftime("%Y-%m-%d %H:%M")}}' 
      icon_template: mdi:clock-start
      unit_of_measurement: ""
      friendly_name: "Starttijd"

Please provide one or two examples of the string value you are trying to convert. Also, what is the error message?

Thanks for your respons.
Errors in log:

Logger: homeassistant.components.template.template_entity
Source: components/template/template_entity.py:73
Integration: Template (documentation, issues)
First occurred: 14:12:47 (1 occurrences)
Last logged: 14:12:47

TemplateError('UndefinedError: 'str object' has no attribute 'strftime'') while processing template 'Template("{{ states("sensor.roborock_vacuum_s5e_last_clean_start").strftime("%m-%-d %H:%M") }}")' for attribute '_attr_native_value' in entity 'sensor.clean_start'

and:

Logger: homeassistant.helpers.event
Source: helpers/template.py:400
First occurred: 14:12:47 (1 occurrences)
Last logged: 14:12:47

Error while processing template: Template("{{ states("sensor.roborock_vacuum_s5e_last_clean_start").strftime("%m-%-d %H:%M") }}")
Traceback (most recent call last):
  File "/usr/src/homeassistant/homeassistant/helpers/template.py", line 398, in async_render
    render_result = _render_with_context(self.template, compiled, **kwargs)
  File "/usr/src/homeassistant/homeassistant/helpers/template.py", line 1698, in _render_with_context
    return template.render(**kwargs)
  File "/usr/local/lib/python3.9/site-packages/jinja2/environment.py", line 1304, in render
    self.environment.handle_exception()
  File "/usr/local/lib/python3.9/site-packages/jinja2/environment.py", line 925, in handle_exception
    raise rewrite_traceback_stack(source=source)
  File "<template>", line 1, in top-level template code
  File "/usr/local/lib/python3.9/site-packages/jinja2/sandbox.py", line 391, in call
    if not __self.is_safe_callable(__obj):
  File "/usr/src/homeassistant/homeassistant/helpers/template.py", line 1907, in is_safe_callable
    return isinstance(obj, AllStates) or super().is_safe_callable(obj)
  File "/usr/local/lib/python3.9/site-packages/jinja2/sandbox.py", line 275, in is_safe_callable
    getattr(obj, "unsafe_callable", False) or getattr(obj, "alters_data", False)
  File "/usr/src/homeassistant/homeassistant/helpers/template.py", line 1724, in _fail_with_undefined_error
    raise ex
  File "/usr/src/homeassistant/homeassistant/helpers/template.py", line 1715, in _fail_with_undefined_error
    return super()._fail_with_undefined_error(*args, **kwargs)
jinja2.exceptions.UndefinedError: 'str object' has no attribute 'strftime'

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/usr/src/homeassistant/homeassistant/helpers/template.py", line 514, in async_render_to_info
    render_info._result = self.async_render(variables, strict=strict, **kwargs)
  File "/usr/src/homeassistant/homeassistant/helpers/template.py", line 400, in async_render
    raise TemplateError(err) from err
homeassistant.exceptions.TemplateError: UndefinedError: 'str object' has no attribute 'strftime'

Value_template without .strftime gives:
value_template: '{{ states("sensor.roborock_vacuum_s5e_last_clean_start") }}'
image

The sensor itself (sensor.roborock_vacuum_s5e_last_clean_start) gives:
image

I also tried: value_template: '{{ states("sensor.roborock_vacuum_s5e_last_clean_end") | timestamp_custom("%m-%-d %H:%M") }}'

Giving the same result as without .strftime (not following template)

Try this:

value_template: "{{ states('sensor.roborock_vacuum_s5e_last_clean_start') | as_datetime | as_timestamp | timestamp_custom('%m-%-d %H:%M') }}"

Thanks for the answer. I tried and it works :ok_hand:

Wouldn’t you rather have a relative time?

If you don’t mind displaying a zero-padded day, you can do this:

value_template: "{{ states('sensor.roborock_vacuum_s5e_last_clean_start')[5:16].replace('T', ' ') }}"

The result is this:

11-05 01:00

I always prefer relative times myself, using your template…

template:
- sensor:
  - name: Clean Start
    unique_id: clean_start
    state: "{{ (states('sensor.roborock_vacuum_s5e_last_clean_start') | as_datetime).isoformat() }}"
    availablity: "{{ states('sensor.roborock_vacuum_s5e_last_clean_start') not in ['unavailable','unknown'] }}"
    device_class: timestamp

then the UI just handles the rest

ThAnks for the reaction.
What do you mean with relative time?

Thanks again.
I did use %d instead of %-d before. Also giving 11-05 1:00
What is the difference?

x days ago, x hours ago, x minutes ago, in x days, etc

Where to learn this kind of templating?
I tried to find information. But hard to find

Ahh I understand.
This is good enough for the moment.
Thanks again

The first example I provided converts a string value like 2021-11-05T01:00:19 to a datetime object then converts that to a integer value (a Unix timestamp) and then converts that to a string value in the desired format.

The second example I provided simply extracts the desired part (11-05 01:00) out of the string value ( 2021-11-05T01:00:19`).

Clear. Thanks for the explanation

I need help creating a time object.

So let’s say I have some kind of homemade device from which I receive data over the RS485 network and
I create two templates: slave6_time and slave6_day,
and collect from them the total time template: slave6_time_day (example 1).

        slave6_time:
            friendly_name: 'RTC Время'
            value_template: "{{ states('sensor.slave6').split(',')[2] | int }}:{{ states('sensor.slave6').split(',')[3] | int }}"
            icon_template: mdi:clock
        slave6_day:
            friendly_name: 'RTC день недели'
            value_template: >-
              {%- set day_num = ["ПН", "ВТ", "СР", "ЧТ", "ПТ", "СБ", "ВС"] %}
              {%- set day_of_week = day_num[ (states('sensor.slave6').split(',')[1] | int)-1 ] %}
              {{ day_of_week }}
            icon_template: mdi:calendar
        slave6_time_day:
            friendly_name: 'RTC День, Время'
            value_template: "{{ states('sensor.slave6_day') }}-{{ states('sensor.slave6_time') }}"
            icon_template: mdi:calendar-clock

All descriptions of the time object that I could find are considered starting from what I take
system time and format it. And it works (example 2).

        system_day_string:
            friendly_name: 'Системное время день'
            value_template: >-
              {%- set day_num = ["ПН", "ВТ", "СР", "ЧТ", "ПТ", "СБ", "ВС"] %}
              {%- set day_of_week = day_num[ (states('sensor.system_day') | int)-1 ] %}
              {{ day_of_week }}
            icon_template: mdi:calendar
        system_time:
            friendly_name: 'Системное время'
            value_template: "{{ as_timestamp(states('sensor.date_time_iso')) | timestamp_custom('%H:%M') }}"
            icon_template: mdi:clock
        system_time_day:
            friendly_name: 'Системное время День, Время'
            value_template: "{{ states('sensor.system_day_string') }}-{{ states('sensor.system_time') }}"
            icon_template: mdi:calendar-clock

The system time is reflected in the GUI correctly,
and the time from my homemade device is read ugly,
because it is not a time object, but just a text string. (example 3).

I tried to use both input_datetime: and template using input_datetime values: (example 4)

  input_datetime:
      slave6_time:
        name: 'RTC Время'
        has_date: false
        has_time: true
        initial: "21:55"
        # initial: "{{ states('sensor.slave6').split(',')[2] | int }} : {{ states('sensor.slave6').split(',')[3] | int }}" #out of order

  sensor:
    - platform: template 
      sensors:
        slave6_custom_time:
            friendly_name: 'RTC custom'
            device_class: 'timestamp'
            # value_template: "{{ states('input_datetime.slave6_time') }}"
            value_template: "21:55:0"
            # attributes:
            #     hour:  "{{ states('sensor.slave6_time_hour') | int}}"

but I don’t know how to assign values ​​from my device to the hour: and minute: attributes,
Or maybe I’m going the wrong way, please tell me:
how to make a custom time object with values ​​from my device,
constantly updating its parameters with the arrival of new time data?

Do not post photos of code. Paste your code here and make sure you format it inside your post.

I can answer my own question, I hope it helps others. Now I have a time object.

slave6:
  sensor:
    - platform: template 
      sensors:
        slave6_custom_time:
            friendly_name: 'RTC объект времени'
            value_template: >
              {% set t_string = states('sensor.slave6').split(',')[2]+':'+ states('sensor.slave6').split(',')[3]    %}
              {%- set t = strptime(t_string, "%H:%M") %}
              {{ t }}

Help me please. I’m trying to count the number of lights on in the Home Assistant template editor. But I get an error UndefinedError: ‘str object’ has no attribute ‘state’

value_template: >
    {% set lights = [
      states('light.1_big_light'),
      states('light.2_big_light_2'),
      states('light.3_big_light_3'),
      ] %}
    {{ lights | selectattr('state','eq','on') | list | count }}

remove states( and ) from each line you use it in. Then replace lights with expand(lights)