Trouble with strptime addition / subtraction

Hey Guys,

I have been pulling my hair out trying to do some time string manipulation without much luck. I have a template sensor which represents a time, and I want to make another sensor based off that. Here is how things look:

  - platform: template
    sensors:
      test_time:
        value_template: '{{ strptime(states.sensor.current_day_time.state , "%a %-I:%M %P") }}'

test_time is working and shows up like this: Thu 5:26 pm

  - platform: template
    sensors:
      test_time2:
        value_template: '{{ strptime(states.sensor.current_day_time.state , "%a %-I:%M %P") - strptime("10", "%M") }}'

test_time2 does not calculate and shows up unknown, but I am expecting it to show Thu 5:16 pm (10 min less than time_test). My log shows this error:

TypeError: unsupported operand type(s) for -: ‘str’ and 'datetime.datetime

As far as I can see from other posts, this subtraction of time should work! I have tried everything I can think of but am out of ideas.

Does anyone have any suggestions?

I couldn’t get your examples to work but maybe this line helps a bit?

{{ strptime(now().strftime("%H:%M:%S"), "%H:%M:%S") - strptime("10", "%M") }}

which evaluates to 15:01:53 for example.

Put this in the template editor to see how it should work:

#datetime
{{now()}}
#timestamp
{{as_timestamp(now())}}
add 1 hour (3600 seconds)
{{as_timestamp(now())+ (1*60*60)}}
display as local time
{{(as_timestamp(now())+ (1*60*60))  | timestamp_local}}
display just the hour
{{(as_timestamp(now())+ (1*60*60))  | timestamp_custom("%H",true)}}
1 Like

Thanks for the help guys but no luck =(

The reason I am using a state in strptime ( and not now() ) is because my phone passes the alarm time to homeassistant (from tasker) and I want to create a new time from this alarm eg. alarmtime - 30min.

My alarm gets passed in either of these formats: Mon 6:30 am OR 9-6-17 06.30 but I cant pass them to strptime without getting the TypeError above. All works well when using now().

I will have to look for some other ways to do this, happy to hear suggestions!

I too was struggling with this same issue, I wanted to create an alarm clock that would start a sequence 15 minutes before the alarm went off. I ended up having to convert the alarm time to a datetime object, convert to epoch, do the subtraction in seconds and then convert it back, this is what I ended up with this which appears to work in my tests so far (in the dev console):

{{ states.sensor.date.state }} / {{ states.sensor.alarm_clock_time.state }}
---
value_template: >-
    {% set alarm = strptime(states.sensor.date.state+' '+states.sensor.alarm_clock_time.state,'%Y-%m-%d %H:%M') %}
2017-06-21 / 06:30
---
value_template: >-
    
    06:15

Here is the entire HA package for reference:

1 Like