Issue: strptime in template not working as expected

Hi!

I’m getting lost in frustration here, hopefully I’m just missing out something really simple…

What I’m trying to achieve is having a time string defined as a datetime helper sorted out in hours and minutes separately.

Sensor config:

- platform: template
  sensors:
    pump_start_h:
      value_template: '{{ strptime(states.input_datetime.pump_startat.state , "%M") }}'
    pump_start_m:
      value_template: '{{ strptime(states.input_datetime.pump_startat.state, "%M") }}'
    pump_stop_h:
      value_template: '{{ strptime(states.input_datetime.pump_stopat.state, "%H") }}'
    pump_stop_m:
      value_template: '{{ strptime(states.input_datetime.pump_stopat.state, "%M") }}'

What I found was that these template sensors were all set as the original date- and timestamps; i.e. 2020-01-01 07:00. The same goes when I try pasting the templates in Templates Dev page.

I then tried entering this into the Templates dev page:

{{ strptime(now() , "%H:%M") }}

Still resulting in full string: 2021-04-28 11:21:00.001145+02:00

Can someone please point out what I’m missing here…?

Thanks!

strptime(string, format) parses a string based on a format and returns a datetime object.

So strptime("12:34", "%H:%M") returns (on my system) a datetime object of 1900-01-01 12:34:00. The format string states how the time you’re giving it is formatted, not how you eventually want it.

input_datetimes are stored as strings in '%H:%M:%S' format. This couldn’t be matched to the format you provided, so was “passed through”. now() returns a datetime object and was passed through as it isn’t a string.

Two different solutions below, using strptime() for the start times and string slicing for the stop times:

- platform: template
  sensors:
    pump_start_h:
      value_template: "{{ strptime(states('input_datetime.pump_startat'), '%H:%M:%S').hour }}"
    pump_start_m:
      value_template: "{{ strptime(states('input_datetime.pump_startat'), '%H:%M:%S').minute }}"
    pump_stop_h:
      value_template: "{{ (states('input_datetime.pump_stopat')[0:2])|int }}"
    pump_stop_m:
      value_template: "{{ (states('input_datetime.pump_stopat')[3:5])|int }}"

Thanks a lot @Troon - that explained it perfectly as well and solved what I was looking for!