REST value template problem with strptime

I would like so set a REST sensor, but do directly some templating on it. It is not delivering a well formated JSON, but I don’t hink that doesn’t matter for my problem.

If I try

  - platform: rest
    name: Next Full Moon
    resource: http://wannistvollmond.celll.net?api=1
    value_template: >
      {{ value ~ "dddd" }}
    scan_interval: 21600    

it is fine

image

but if I use a working template from dev tools

{{ strptime("23.04.2024 23:50","%d.%m.%Y %H:%M") + timedelta(hours=2) }}

image

for the sensor

  - platform: rest
    name: Next Full Moon
    resource: http://wannistvollmond.celll.net?api=1
    value_template: >
      {{ strptime(value,"%d.%m.%Y %H:%M") + timedelta(hours=2) }}
    scan_interval: 21600

I get

ValueError: Template error: strptime got invalid input '23.04.2024 23:50' when rendering template '{{ strptime(value,"%d.%m.%Y %H:%M") + timedelta(hours=2) }}' but no default was specified

and with a default only the default. But where and how is the problem, as afaik it is not an invalid input and working elsewhere as well?

I agree it’s puzzling. From all outward appearances, strptime should be able to process the string.

In similar cases that I have encountered, the cause was the presence of unprintable characters in the string (like nulls). The unprintable character isn’t displayed but it’s present so it interferes with filters, like strptime, that attempt to process the string.

If it does contain unprintable characters (and that’s just speculation) they must be removed. If there’s a null character at the end of the string, the trim filter might remove it (I say “might” because I don’t know for sure what kind of characters it removes beyond spaces and tabs).

As a first experiment, try this version. It simply uses trim to remove leading and trailing whitespace.

{{ strptime(value | trim, "%d.%m.%Y %H:%M") + timedelta(hours=2) }}

If that fails to fix the problem, try this version. It converts the value to a slug (a string containing only alphanumeric characters and underscores), changes underscores to spaces, removes leading and trailing whitespace, then uses a slightly different pattern in strptime to convert the string to a datetime object.

{{ strptime(value | slugify | replace('_', ' ') | trim, "%d %m %Y %H %M") + timedelta(hours=2) }}

If that also fails to fix the problem, I’m not sure what else can be done. Maybe there are no unprintable characters and it’s due to something completely different.

1 Like

Thx so much. trim was not enough and just only the slug did the trick / was enough.

{{ strptime("23.04.2024 23:50"|slugify, "%d_%m_%Y_%H_%M") + timedelta(hours=2) }}

But ofc I saved the whole ideas for reference.

1 Like