Need help with template sensor for calculating time

I have a feedparser sensor from a news podcast:

  - platform: feedparser
    name: Nachrichten
    feed_url: 'https://www.deutschlandfunk.de/podcast-nachrichten.1257.de.podcast.xml'
    date_format: '%H:%M'
    scan_interval: 120

Now I want to have a template sensor that gives me the time in minutes/hours since the last news podcast was published, that’s what I have so far:

  - platform: template
    sensors:
      last_news_ago:
        friendly_name: 'Letzte Nachrichten'
        entity_id: sensor.date_time
        value_template: >-
              {% set newshours = (states.sensor.nachrichten.attributes.entries[0].title.split(',')[1].split(':')[0] | int) *60 %}
              {% set newsmin = (states.sensor.nachrichten.attributes.entries[0].title.split(',')[1].split(':')[1].split(' Uhr')[0] | int) %}
              {% set newstotal = newshours + newsmin | int %}
              {% set nowhours = (now().hour | int) *60 %}
              {% set nowminutes = (now().minute | int) %}
              {% set nowtotal = nowhours + nowminutes | int %}
              {% set newsnow = nowtotal - newstotal   | int %}
              {% if newsnow > 60 %}{{ newsnow// 60 }}:{{ '{:0>2d}'.format(newsnow%60) }} hours{% else %}{{newsnow}} Minuten{% endif %}

states.sensor.nachrichten.attributes.entries[0].title will display “Nachrichten vom 30.07.2020, 21:00 Uhr”
for example, so first I tried to extract the time ( 21:00) and then added hours and minutes together, get the actual time and in the last step I subtract the minutes from the news podcast from the actual time.
It works fine, but only if the news podcast was released on the same day. For example if the last podcast was published at 23 o’clock and its already 1 o’clock in the morning it gives me -1370 Minutes or something back. How can I fix this?

{% set a = "Nachrichten vom 30.07.2020, 21:00 Uhr" %}
{% set b = a.split(' ')[2:] %}
{% set c = b[0][:-1].split('.') %}
{% set d = c[2]~'-'~c[1]~'-'~c[0]~'T'~b[1] %}
{% set ts = strptime(d, '%Y-%m-%dT%H:%M') %}
{{ ((now()|as_timestamp() - ts|as_timestamp())/60)|int }}

EDIT: Phil’s is better :heart_eyes:

1 Like
{% set secs = (
     now().replace(tzinfo=none) -
     strptime(states.sensor.nachrichten.attributes.entries[0].title,
              'Nachrichten vom %d.%m.%Y, %H:%M Uhr')
   ).total_seconds() %}

Will calculate the number of seconds since that date/time. Then you can reformat as you like.

1 Like

thank you very much @pnbruckner and @Troon! - Both working perfect!