Get date of Monday of the actual week

I’m looking for a way to get the date of the Monday of the actual week. So if today is 2020-08-26, a template sensor should display 2020-08-24, the date of last Monday.
I know that is possible with the shell command date -v -Mon +%Y-%m-%d, but as far as I know, that’s not possible in Home Assistant. Does anybody know a different solution?

{{ now().weekday() }}
Returns 2 since today is Wednesday.

So if you take today’s date and subtract the above template then you will get the answer.

But then there is the old question, what day of the week so you consider start of week.
If you think Sunday then it will be slightly more complex.

Edit:

{{ (now().timestamp() - now().weekday() *86400) | int | timestamp_custom("%Y-%m-%d") }}

This will work most of the year. It will be incorrect at DST time, meaning in the middle of the night when the time switches.
This is because it’s a hard coded 86400, It can be made better but I don’t believe there is a need for that.

1 Like

I made a template sensor with the code and it seems to work! Thank you very much @Hellis81 - I´m glad my week starts with Monday :slight_smile: - No problem with the incorrect sensor value at night, I need it only once a day, so I will have a long scan_interval

Thanks for this very useful post. You said that if you are looking for something other than the previous Monday then it is more complicated. So for the benefit of other people who are wanting that extra detail, here is a closely related example, returning the date of next Sunday:

Next Sunday: {{ (now().timestamp()+(6-now().weekday())*86400) | int | timestamp_custom("%Y-%m-%d") }}

I need something similar. I am trying to scrape the URL for school’s schedule. URL has always the Friday’s date in YYYY-MM-DD format and for each day, selectors are named based on the date in the same format.
I am trying to find a convenient way to find current and next week Friday’s date as well as each day in current/next week. Anyone has any idea?
One of the ways could be that I would scrape URL only at given time of week, but I am looking for something more elegant that won’t fail if I decide to scrape it at another time.

A lot has changed since this thread was created.

But this should give you this week and next week’s Friday:

this week
{% set wd = 4 %}
{% if now().weekday() == wd %}
  {{ now().date() }}
{% else %}
  {{ (now() + timedelta(days = wd - now().weekday())).date() }}
{% endif %}

next week
{% set wd = 4 %}
{% if now().weekday() == wd %}
  {{ now().date() + timedelta(days = 7) }}
{% else %}
  {{ (now() + timedelta(days = wd - now().weekday() + 7)).date() }}
{% endif %}
1 Like

Thanks a lot, works like a charm.