Hi, I’m new to Home Assistant and could use some help. I’m trying to input a list of bus timings for a private bus stop and have it track the next upcoming bus. However, I keep getting a message saying, “there are no more buses today.” I have the code save inside the configuration.yaml file as follow. Any help will be very much appreciated. Thank you.
sensor:
- platform: template
sensors:
next_bus_stop_a_debug:
friendly_name: "Next Bus at Bus Stop A (Debug)"
value_template: >
{% set current_time = now().strftime('%H:%M') %}
{% set is_weekend = now().weekday() in [5, 6] %}
{% set bus_stop_a_weekday_schedule = "06:30, 07:30, 08:30, 09:30, 10:30, 12:00, 13:00, 14:00, 16:00, 18:00" %}
{% set bus_stop_a_weekend_schedule = "09:00, 10:00, 11:00, 12:00, 13:00, 14:00, 16:00, 18:00" %}
{% set bus_times_raw = bus_stop_a_weekend_schedule if is_weekend else bus_stop_a_weekday_schedule %}
{# Debugging to print the raw schedule #}
{% set debug_schedule = "Bus times (raw): " ~ bus_times_raw %}
{# Split and clean the bus times #}
{% set times_list = bus_times_raw.split(',') %}
{% set cleaned_times_list = times_list | map('trim') | list %}
{# Convert current time to a full datetime object #}
{% set current_time_obj = strptime(now().strftime('%Y-%m-%d ') ~ current_time, '%Y-%m-%d %H:%M') %}
{% set debug_current_time = "Current time: " ~ current_time ~ " (datetime: " ~ current_time_obj ~ ")" %}
{# Initialize next bus variable #}
{% set next_bus = None %}
{# Compare each bus time after converting to a datetime object #}
{% for time in cleaned_times_list %}
{% set full_bus_time_str = now().strftime('%Y-%m-%d ') ~ time %}
{% set bus_time_obj = strptime(full_bus_time_str, '%Y-%m-%d %H:%M') %}
{% if bus_time_obj > current_time_obj %}
{% set next_bus = time %}
{% break %}
{% endif %}
{% endfor %}
{# Output debugging information and next bus #}
{{ next_bus if next_bus else "No more buses today" }}
Debug: {{ debug_schedule }} | {{ debug_current_time }}