Get HASS Date Format from Custom Component

I noticed that the Date Format option was added to the Profile settings recently. I was hoping someone knew how I might be able to identify that Date Format value from a component in Python?

I can get the HASS Time Zone using hass.config.time_zone but I’ve not found the Date Format in hass.config or anywhere else.

It is part of the user config (and therefore can vary by user) so not part of the hass object. There doesn’t seem to be any functions to get this info for a user, only webservices for the frontend to retrieve it. Code is here:

Ok, then maybe I need a different approach. Any way to get the default date format (Month and Date only) for an area from the HASS Time Zone, Language, and/or Country?

What are you trying to achieve? If you set a sensor or attribute value to a datetime the frontend display will render it in the users format.

In places, there is an option to show when the state last changed at the end of the state (ex. Home (since 20:05)). After 24 hours in the same place, the state then changes from the time to the date it was last changed (ex. Home (since 08/28)). I’m trying to have the date to respect the regions preferred date format: mm/dd, dd/mm, mm-dd, dd-mm, mm.dd, dd.mm, etc.

I am currently using locale to get the date format of the system’s locale. It works, however many systems’ locale doesn’t seem to be set correctly and would prefer to use what is set in HASS.

Current code:

import locale
from datetime import datetime, timedelta

localedate = str(locale.nl_langinfo(locale.D_FMT)).replace(" ", "")
if localedate.lower().endswith("%y"):
  localemmdd = localedate[:-3]
elif localedate.lower().startswith("%y"):
  localemmdd = localedate[3:]
else:
  localemmdd = "%m/%d"
            
mmddstring = (
  datetime.fromisoformat(self.get_attr(ATTR_LAST_CHANGED))
  .strftime(f"{localemmdd}")
  .replace(" ", "")[:5]
)
self.set_attr(
  ATTR_NATIVE_VALUE,
  f"{self.get_attr(ATTR_NATIVE_VALUE)[: -14]}" + f" (since {mmddstring})",
)

Hmm, maybe someone more knowledgable than me may provide a better answer but i dont think you can do this like you are looking to do. As the sensor state is the same for all users, you have to rely on the frontend to format dates for the user as 2 users can have different date format settings on the same system. As your attribute is text, it will not format in the frontend.

The only thing i can think to do is use get_age to show this a 10 mins ago, 2 days ago, 1 month ago etc. This can be imported from homeassistant.util.dt.py.