Template warning: 'strptime' got invalid input

Hello there,

I’m using strptime to report on the last_changed time of an entity. I’m getting a lot of these entries in my log (manually formatted for your viewing pleasure):

2022-03-01 17:54:22 WARNING (MainThread) [homeassistant.helpers.template]
Template warning: 'strptime' got invalid input '2022-03-01 05:22:51.684293+00:00' when rendering template
'{% set value = states.binary_sensor.kitchen_motion_motion.last_changed %}
 {% set last_updated = as_timestamp(strptime(value, "%Y-%m-%d %H:%M:%S.%f%z")) %}
 {% set seconds = (now().timestamp() - last_updated) | round(0) %}
 {{ seconds }}'
but no default was specified.
Currently 'strptime' will return '2022-03-01 05:22:51.684293+00:00', however
this template will fail to render in Home Assistant core 2022.1

There are many similar entries.

This seems like a mismatch between the date (in this case 2022-03-01 05:22:51.684293+00:00 and the strptime format ("%Y-%m-%d %H:%M:%S.%f%z") but I just can’t spot where the problem is.

In fact, running this in python by importing datetime and using datetime.datetime.strptime() with this exact date string and format works perfectly.

Any ideas?

The strptime function expects to receive a string to convert to a datetime object. However, last_changed contains a datetime object, not a string.

Copy-paste the following template into the Template Editor and you’ll see it reports elapsed time in seconds.

{{ (now() - states.binary_sensor.kitchen_motion_motion.last_changed).total_seconds() | round(0) }}

Ah, that makes perfect sense. I wondered myself why last_changed wasn’t a datetime object, but being a noob in homeassistant, I decided to trust other people’s code… :slight_smile:

I’ll test it and report back (but it makes all the sense that it should work).

Thanks.