Weekday and month sensor

As you’ll notice, I have a preconfigured Dark Sky sensor, a Google Travel Time sensor and a datetime sensor.
Beware the Dark Sky sensor only works if you have enabled

forecast:
  - 0

in the dark sky sensor configuration.

Here is mine:

- platform: darksky
  api_key: !secret dark_sky_api_key
  latitude: !secret latitude
  longitude: !secret longitude
  units: si
  forecast:
    - 0
  monitored_conditions:
    - summary
    - icon
    - precip_type
    - precip_intensity
    - precip_probability
    - temperature
    - temperature_high
    - apparent_temperature
    - dew_point
    - wind_speed
    - wind_bearing
    - cloud_cover
    - humidity
    - pressure
    - visibility
    - ozone
    - hourly_summary
    - daily_summary
    - uv_index

If you use sensor.time to trigger the template sensor, it will trigger every minute. This is needlessly frequent for a sensor that only needs to recalculate once a day.

Use sensor.date which will trigger once at the beginning of each day. To simplify the templates, use strftime. It can provides the names of the day and month (exclusively in English in Home Assistant).

- platform: template
  sensors:
    dayoftheweek:
      entity_id: sensor.date
      value_template: "{{ now().strftime('%A') }}"

    month:
      entity_id: sensor.date
      value_template: "{{ now().strftime('%B') }}"

    dateofthemonth:
      entity_id: sensor.date 
      value_template: >
        {% set suffix = ['st', 'nd', 'rd'] %}
        {% set day = now().day %}
        {% set index = 3 if day // 10 == 1 or day % 10 == 0 else (day % 10) - 1 %}
        {{ day~'th' if index > 2 else day~suffix[index] }}

EDIT

  • Added qualification that strftime reports names exclusively in English in Home Assistant.
  • Updated dateofthemonth template to properly support exceptions: 1st, 2nd, 3rd, 11th, 12th, 13th, 21st, 22nd, 23rd, 31st.
8 Likes

The only reason the list was used is for people who don’t use English. Yeah the 1st 2 templates ‘%A’ and ‘%B’ are great for english speakers, but any other language will not work.

1 Like

According to the documentation for strftime, they’ll be rendered using the locale’s setting.
https://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior

%A
Weekday as locale’s full name.
Sunday, Monday, …, Saturday (en_US); Sonntag, Montag, …, Samstag (de_DE)

I haven’t tested it in Home Assistant. If it always defaults to English then I guess Home Assistant doesn’t support locale?

It’s always English in home assistant. It does not change the datetime locale.

1 Like

OK. Then for all those who need a language other than English, they can continue to use the other examples that have been provided (using a list).

Hi,

I am sorry to raise an old thread, but I get this error when using your exact code. (I had amended it to my own, but then when I got the error I input yours but am still getting the error.

Can you help?

Error loading /config/configuration.yaml: while scanning for the next token
found character '%' that cannot start any token
  in "/config/scripts.yaml", line 363, column 17

Hi, I managed to solve this by moving “Good” to the front, and removing it from the morning, afternoon, evening…

Hi UIGUY, great you got it working. Can you share the code?
It works perfectly and has done for many versions with me.
Can you send an example of your faulty code?

I was wondering how to make a sensor that senses a day of the week relative to today.

So a sensor that would know today is Saturday and then tell me that in 2 days its Monday.

Something like this should work:

  - platform: time_date
    display_options:
      - 'time'
      - 'date'
      - 'date_time'
      - 'date_time_iso'
      - 'time_date'
      - 'time_utc'
      - 'beat'

  - platform: template
    sensors:
      days_until_monday:
        value_template: >
          {{ (7 - now().weekday()) % 7 }}
        entity_id: sensor.date

now().weekday() returns a number representing the day of the week (0 for Monday and 6 for Sunday). Subtract that from 7 and calculate the remainder of the division by (modulo) 7 and you have the number of days until Monday.

Note that you have to refer to an entity that is updated from time to time (such as sensor.time or sensor.date - the latter changes once a day which should be enough) in order to update the sensor (the sensor only updates on state changes, and now() is a function and does not have a state, so the sensor won’t update unless you refer to an entity as shown in the example).

Wow - I have no idea how you came up with that algorithm for the st, nd, rd, and th - that’s absolutely brilliant! I had to plug it all into the developer template to figure it out. It’s now part of my sensors. Thanks, @123!

I’m trying to get the weekday and the next five weekdays on a weather forecast card. If today is Thursday, I want to have Friday to Tuesday displayed as the next five days.

I created 6 sensors, adding the desired number of days on each card:

  - platform: template
    sensors:
      dayoftheweek:
        value_template: "{{ ['Maandag','Dinsdag','Woensdag','Donderdag','Vrijdag','Zaterdag','Zondag'][now().weekday()] }}"
      dayoftheweek1:
        value_template: "{{ ['Maandag','Dinsdag','Woensdag','Donderdag','Vrijdag','Zaterdag','Zondag'][now().weekday()+1] }}"
      dayoftheweek2:
        value_template: "{{ ['Maandag','Dinsdag','Woensdag','Donderdag','Vrijdag','Zaterdag','Zondag'][now().weekday()+2] }}"

Etcetera.

This works, however only for days within the current week: Monday and Tuesday are not displayed. It makes sense, as weekday 8 and 9 do not exist. Any ideas how to resolve this?

@mcwieger

  - platform: template
    sensors:
      dayoftheweek:
        value_template: "{{ ['Maandag','Dinsdag','Woensdag','Donderdag','Vrijdag','Zaterdag','Zondag'][now().weekday()] }}"
      dayoftheweek1:
        value_template: "{{ ['Maandag','Dinsdag','Woensdag','Donderdag','Vrijdag','Zaterdag','Zondag'][(now().weekday()+1) % 7] }}"
      dayoftheweek2:
        value_template: "{{ ['Maandag','Dinsdag','Woensdag','Donderdag','Vrijdag','Zaterdag','Zondag'][(now().weekday()+2) % 7] }}"

That is something I neither would ever have figured out myself nor something I understand.

It works though, so thanks a lot!

If you understand what you did before then simply look up mod(ulo) operation :slight_smile:

Sorry to resurrect (again) an old thread, but is there a way to change the starting day of week to Sunday = 0, instead of Monday? Without going into the exhaustive historical reasons why this is accurate, suffice it to say that I’m struggling to code based on Monday being the first day, which should be Sunday. Maybe it’s just too late at night (CT, USA) and my brain can’t figure out the conversion… Thanks

strftime('%w') returns a value where 0 represents Sunday and 6 is Saturday.

Example:

{{ ['Zondag','Maandag','Dinsdag','Woensdag','Donderdag','Vrijdag','Zaterdag'][now().strftime('%w')|int(0)] }}
1 Like

Btw, unless you are a frequent time traveller or want to gain programming experience, displaying the current date in Home Assistant adds no value.

Value is in the eye of the beholder.
I missed a few hours of work the other day because I thought it was Tuesday, when it was Wednesday.
Its easy to loose track of the day of week when you work 8 days on, 6 days off. 14 day work schedule. Its all a blur.
Say that “day of week” has no value again.

1 Like

We use the sensor as a template for the morning briefing scripts to play on the speakers every workday morning after the alarm rings.