Make timedelta from string that's either HH:MM:SS or MM:SS

I have a sensor that returns a string that may contain the duration of an event in hours:minutes:seconds or minutes:seconds (if it’s less than 1 hour). I’m having trouble converting that to a timedelta value. I need to calculate the end-time of an event, of which I have the start:
{{ strptime(now().year|string+"."+state_attr("sensor.strava_0_0","friendly_name"),"%Y.%d.%m. - %H:%M")-now().replace(tzinfo=None) > timedelta(hours=-12)}}
and the duration, in an initially unkonwn format, containing hours or only minutes and seconds.
I can get it working if I know which of the two it is. But I cannot detect it.
Can I detect if something is a string or a time value? Then I could check if the first conversion (from %H:%M:%S) fails and fall back to the %M:%S format.

I got it working. The intention is to calculate how long ago my last activity on Strava finished:

{% set startTimeString = state_attr("sensor.strava_0_0","friendly_name") %}
{% set durationString = states("sensor.strava_0_1") %}
{% set duration = strptime(durationString, "%H:%M:%S")  %}
{% if duration.hour is defined %}
  {% set delta = timedelta(hours=duration.hour,minutes=duration.minute,seconds=duration.second) %}
{% else %}
  {% set duration = strptime(durationString, "%M:%S")  %}
  {% set delta = timedelta(minutes=duration.minute,seconds=duration.second) %}
{% endif %}
{{ now().replace(tzinfo=None)-strptime(now().year|string+"."+startTimeString,"%Y.%d.%m. - %H:%M")-delta < timedelta(hours=2) }}

If you’re interested, you can reduce the template to this (it requires version 2022.2.0 or higher because it uses iif):

{% set start = strptime('{}.{}'.format(now().year, state_attr('sensor.strava_0_0', 'friendly_name')), '%Y.%d.%m. - %H:%M') | as_local %}
{% set duration = states('sensor.strava_0_1') %}
{% set duration = iif(duration.count(':') == 1, '00:' ~ duration, duration) %}
{% set h,m,s = duration.split(':') | map('int') | list %}
{{ now() - start - timedelta(hours=h, minutes=m, seconds=s) < timedelta(hours=2) }}
2 Likes