Timestamp to time

I have “created” (more or less copy/paste from another HA user) a timestamp sensor that locates the cheapest continues hours to charge my EV car and it returns the start-time. It returns “17 februari 2023 kl. 22:00”.

I now want to move the time in format HH:MM to a helper (input_datetime.customvirtual_ev_starttid_for_smartladdning) to use in automations. I have put the following service call action in an automation to handle this specific function, but it doesn’t work. I have googled the issue and it seems to work for others.

service: input_datetime.set_datetime
data:
  time: '{{ as_timestamp(states('sensor.sensor_ev_cheapest_hours_start')) | timestamp_custom("%H:%M") }}'
target:
  entity_id: input_datetime.customvirtual_ev_starttid_for_smartladdning

When I run the automation, nothing happens. When I go back to the code and review it, it turns up as follows:

service: input_datetime.set_datetime
data:
  time:
    as_timestamp(states('sensor.sensor_ev_cheapest_hours_start')) | timestamp_custom(''%H:%M''): null
target:
  entity_id: input_datetime.customvirtual_ev_starttid_for_smartladdning

What am I missing here?

Copy the following template into the Template Editor. You’ll see that as_timestamp is unable to convert the supplied datetime string into a timestamp value.

{{ as_timestamp("17 februari 2023 kl. 22:00") }}

This works for me:

{{ strptime("17 February 2023 kl. 22:00", "%d %B %Y kl. %H:%M", None) }}
Result: 2023-02-17 22:00:00

But not this:

{{ strptime("17 februari 2023 kl. 22:00", "%d %B %Y kl. %H:%M", None) }}
Result: null

Correct, because in Home Assistant, python defaults to English (strptime is a python string method). As a result, it makes it more challenging to convert non-English datetime strings into a datetime object.

1 Like

What is the diffeerence in using as_timestamp and strptime?

Is there any known work-arounds?

A little kludgy, but could you do something like this:

{% set chargetime = states(‘sensor.sensor_ev_cheapest_hours_start’) %}
{% set chargetime = chargetime | replace(‘januari’,‘January’) %}
{% set chargetime = chargetime | replace(‘februari’,‘February’) %}

{% set chargetime = chargetime | replace(‘desember’,‘December’) %}

{{ strptime(chargetime, “%d %B %Y kl. %H:%M”, None) }}

Is this sensor.sensor_ev_cheapest_hours_start a template sensor? If so, could you please share the yaml?
Otherwise, from where is this data coming?

Also, if you go to Developer Tools > State and search for this sensor, what can you see on the State and Attributes columns?

sensor:
  - platform: template
    sensors:
      sensor_ev_cheapest_hours_start:
        device_class: timestamp
        friendly_name: Sensor - EV Cheapest hours start
        value_template: >

          {% set numberOfSequentialHours = states('input_number.customvirtual_ev_antal_timmar_att_ladda') | int() %}
          {% set lastHour = 24 %}
          {% set firstHour = 0 %}

          {% if state_attr('sensor.nordpool_kwh_se3_sek_1_10_025', 'tomorrow_valid') == true and state_attr('sensor.nordpool_kwh_se3_sek_1_10_025', 'tomorrow') [1] is number == true %}
            {% set ns = namespace(counter=0, list=[], cheapestHour=today_at("00:00") + timedelta( hours = (24)), cheapestPrice=999.00) %}
            {% for i in range(firstHour + numberOfSequentialHours, lastHour +25 ) %}
              {% set ns.counter = 0.0 %}
              {% for j in range(i-numberOfSequentialHours, i) %}
                {% if j < 24 %}
                  {% set ns.counter = ns.counter + state_attr('sensor.nordpool_kwh_se3_sek_1_10_025', 'today')[j] %}
                {% else %}
                  {% set ns.counter = ns.counter + state_attr('sensor.nordpool_kwh_se3_sek_1_10_025', 'tomorrow')[j-24] %}
                {% endif %}
              {% endfor %}
              {% set ns.list = ns.list + [ns.counter] %}
              {% if ns.counter < ns.cheapestPrice %}
                {% set ns.cheapestPrice = ns.counter %}
                {% set ns.cheapestHour=today_at("00:00") + timedelta( hours = (i - numberOfSequentialHours )) %}
              {% endif %}
            {% endfor %}
            {{ ns.cheapestHour }}
            {% set ns.cheapestPrice = (ns.cheapestPrice / numberOfSequentialHours) %}
          {% else %}
            {% set ns = namespace(counter=0, list=[], cheapestHour=today_at("00:00") + timedelta( hours = (24)), cheapestPrice=999.00) %}
            {% for i in range(firstHour + numberOfSequentialHours, lastHour + 1) %}
              {% set ns.counter = 0.0 %}
              {% for j in range(i-numberOfSequentialHours, i) %}
                {% set ns.counter = ns.counter + state_attr('sensor.nordpool_kwh_se3_sek_1_10_025', 'today')[j] %}
              {% endfor %}
              {% set ns.list = ns.list + [ns.counter] %}
              {% if ns.counter < ns.cheapestPrice %}
                {% set ns.cheapestPrice = ns.counter %}
                {% set ns.cheapestHour = today_at("00:00") + timedelta( hours = (i - numberOfSequentialHours )) %}
              {% endif %}
            {% endfor %}
            {{ ns.cheapestHour }}
            {% set ns.cheapestPrice = (ns.cheapestPrice / numberOfSequentialHours) %}
          {% endif %}

Why are you trying to move the info to a helper? What is your final goal (how are you gonna use this helper)?

I want it to be used as a trigger in an automation to start the charger, if the car is connected.

When changing to english in my settings for HA, I get the correct format, though the issue remains.

You probably don’t need a helper in this case, as you already have the value in your original sensor and you can use that in your automation…

But let’s leave this for a bit later… Share how this sensor is created and we might be able to help better.

I did, a few posts above.

I really appriciate all of you taking the time to help.

This sensor is probably already in the format you need… You see in you language in the UI, but in the back is using proper format.

Could you share a screenshot of this sensor in Developer Tools > States?

This is Developer Tools > Templates…
Probably will be easier to visualise if you share Developer Tools > States (filtering to that sensor you created).

But I can already see you have the right format (or almost)

Look, I have to go to sleep now, but I promise I will take a look at this if no one else helps you tonight…

So, now I could test your sensor and can confirm it return a valid timestamp, so you can use it as it is in your automation, without the need to store in a input helper, or you can still save to your input helper, but in this case you don’t have to do any transformation.

It is as simple as this:

service: input_datetime.set_datetime
data:
  datetime: "{{ states('sensor.sensor_ev_cheapest_hours_start') }}"
target:
  entity_id: input_datetime.customvirtual_ev_starttid_for_smartladdning

But again, you are using an automation to take a value from a sensor, transfer that value to an input helper without any transformation, so you will use the input helper as an input in another automation, right? Why don’t you simplify this by just using your original sensor (sensor.sensor_ev_cheapest_hours_start) in the final automation, with no need for a helper?

Take a look at this example using sensor on the documentation. It requires the sensor to have state_class: timestamp, which is your case:

So your automation will be something like this:

automation:
  - trigger:
      - platform: time
        at: sensor.sensor_ev_cheapest_hours_start
    action:
      - service: switch.turn_on
        target:
          entity_id: switch.car_charger

Based on the investigation performed by EdwardTFN, it appears you don’t need a workaround. You have a Template Sensor configured as a timestamp sensor. You should be able to use it directly in a Time Trigger (see EdwardTFN’s example).

For future reference, when you tell people the value of an entity, report the value you see in Developer Tools > States. That’s the entity’s actual state value. What you see displayed elsewhere in the UI might be reformatted (in your native language or for cosmetic purposes).

1 Like