Hanafi --- islamic_prayer_time

Tags: #<Tag:0x00007f7810c10f18>

As-Salaam and good day.

I am trying to make the islamic_prayer_time sensor.py accept “school” as a parameter.

I took the original sensor.py code from GitHub, but I cant get it to work. Can anyone help. Here is my code:
“”“Platform to retrieve Islamic prayer times information for Home Assistant.”""
import logging
from datetime import datetime, timedelta

import voluptuous as vol

import homeassistant.helpers.config_validation as cv
import homeassistant.util.dt as dt_util
from homeassistant.components.sensor import PLATFORM_SCHEMA
from homeassistant.const import DEVICE_CLASS_TIMESTAMP
from homeassistant.helpers.entity import Entity
from homeassistant.helpers.event import async_track_point_in_time

_LOGGER = logging.getLogger(name)

PRAYER_TIMES_ICON = “mdi:calendar-clock”

SENSOR_TYPES = [“fajr”, “sunrise”, “dhuhr”, “asr”, “maghrib”, “isha”, “midnight”]

CONF_CALC_METHOD = “calculation_method”
CONF_CALC_SCHOOL = “calculation_school”
CONF_SENSORS = “sensors”

CALC_METHODS = [“karachi”, “isna”, “mwl”, “makkah”]
CALC_SCHOOL = [“0”, “1”]
DEFAULT_SENSORS = [“fajr”, “dhuhr”, “asr”, “maghrib”, “isha”]

vol.Optional(CONF_CALC_METHOD, default=DEFAULT_CALC_METHOD): vol.In(
vol.Optional(CONF_CALC_SCHOOL, default=DEFAULT_CALC_SCHOOL): vol.In(
vol.Optional(CONF_SENSORS, default=DEFAULT_SENSORS): vol.All(
cv.ensure_list, vol.Length(min=1), [vol.In(SENSOR_TYPES)]

async def async_setup_platform(hass, config, async_add_entities, discovery_info=None):
“”“Set up the Islamic prayer times sensor platform.”""
latitude = hass.config.latitude
longitude = hass.config.longitude
calc_method = config.get(CONF_CALC_METHOD)
calc_school = config.get(CONF_CALC_SCHOOL)

if None in (latitude, longitude):
    _LOGGER.error("Latitude or longitude not set in Home Assistant config")

prayer_times_data = IslamicPrayerTimesData(latitude, longitude, calc_method, calc_school)

prayer_times = prayer_times_data.get_new_prayer_times()

sensors = []
for sensor_type in config[CONF_SENSORS]:
    sensors.append(IslamicPrayerTimeSensor(sensor_type, prayer_times_data))

async_add_entities(sensors, True)

# schedule the next update for the sensors
await schedule_future_update(
    hass, sensors, prayer_times["Midnight"], prayer_times_data

async def schedule_future_update(hass, sensors, midnight_time, prayer_times_data):
“”"Schedule future update for sensors.

Midnight is a calculated time.  The specifics of the calculation
depends on the method of the prayer time calculation.  This calculated
midnight is the time at which the time to pray the Isha prayers have

Calculated Midnight: The Islamic midnight.
Traditional Midnight: 12:00AM

Update logic for prayer times:

If the Calculated Midnight is before the traditional midnight then wait
until the traditional midnight to run the update.  This way the day
will have changed over and we don't need to do any fancy calculations.

If the Calculated Midnight is after the traditional midnight, then wait
until after the calculated Midnight.  We don't want to update the prayer
times too early or else the timings might be incorrect.

calculated midnight = 11:23PM (before traditional midnight)
Update time: 12:00AM

calculated midnight = 1:35AM (after traditional midnight)
update time: 1:36AM.

_LOGGER.debug("Scheduling next update for Islamic prayer times")

now = dt_util.as_local(dt_util.now())
today = now.date()

midnight_dt_str = "{}::{}".format(str(today), midnight_time)
midnight_dt = datetime.strptime(midnight_dt_str, "%Y-%m-%d::%H:%M")

if now > dt_util.as_local(midnight_dt):
        "Midnight is after day the changes so schedule update "
        "for after Midnight the next day"

    next_update_at = midnight_dt + timedelta(days=1, minutes=1)
        "Midnight is before the day changes so schedule update for the "
        "next start of day"

    tomorrow = now + timedelta(days=1)
    next_update_at = dt_util.start_of_local_day(tomorrow)

_LOGGER.debug("Next update scheduled for: %s", str(next_update_at))

async def update_sensors(_):
    """Update sensors with new prayer times."""
    # Update prayer times
    prayer_times = prayer_times_data.get_new_prayer_times()

    _LOGGER.debug("New prayer times retrieved.  Updating sensors.")

    # Update all prayer times sensors
    for sensor in sensors:

    # Schedule next update
    await schedule_future_update(
        hass, sensors, prayer_times["Midnight"], prayer_times_data

async_track_point_in_time(hass, update_sensors, next_update_at)

class IslamicPrayerTimesData:
“”“Data object for Islamic prayer times.”""

def __init__(self, latitude, longitude, calc_method, calc_school):
    """Create object to hold data."""
    self.latitude = latitude
    self.longitude = longitude
    self.calc_method = calc_method
self.calc_school = calc_school
    self.prayer_times_info = None

def get_new_prayer_times(self):
    """Fetch prayer times for today."""
    from prayer_times_calculator import PrayerTimesCalculator

    today = datetime.today().strftime("%Y-%m-%d")

    calc = PrayerTimesCalculator(

    self.prayer_times_info = calc.fetch_prayer_times()
    return self.prayer_times_info

class IslamicPrayerTimeSensor(Entity):
“”“Representation of an Islamic prayer time sensor.”""

ENTITY_ID_FORMAT = "sensor.islamic_prayer_time_{}"

def __init__(self, sensor_type, prayer_times_data):
    """Initialize the Islamic prayer time sensor."""
    self.sensor_type = sensor_type
    self.entity_id = self.ENTITY_ID_FORMAT.format(self.sensor_type)
    self.prayer_times_data = prayer_times_data
    self._name = self.sensor_type.capitalize()
    self._device_class = DEVICE_CLASS_TIMESTAMP
    prayer_time = self.prayer_times_data.prayer_times_info[self._name]
    pt_dt = self.get_prayer_time_as_dt(prayer_time)
    self._state = pt_dt.isoformat()

def name(self):
    """Return the name of the sensor."""
    return self._name

def icon(self):
    """Icon to display in the front end."""

def state(self):
    """Return the state of the sensor."""
    return self._state

def should_poll(self):
    """Disable polling."""
    return False

def device_class(self):
    """Return the device class."""
    return self._device_class

def get_prayer_time_as_dt(prayer_time):
    """Create a datetime object for the respective prayer time."""
    today = datetime.today().strftime("%Y-%m-%d")
    date_time_str = "{} {}".format(str(today), prayer_time)
    pt_dt = dt_util.parse_datetime(date_time_str)
    return pt_dt

async def async_update(self):
    """Update the sensor."""
    prayer_time = self.prayer_times_data.prayer_times_info[self.name]
    pt_dt = self.get_prayer_time_as_dt(prayer_time)
    self._state = pt_dt.isoformat()


bump. Please help

Did you got this to work?

Hi. No I have not sorted it out yet. I moved over to Hass.io and I am trying to get custom_components working. I dont like Hass.io

Once I get that working, I will try to get Hanafi time working


This is my solution. Next is to setup a media server to play adhaan, and other sounds like doorbell, alarm etc.


  • platform: rest
    name: “Prayer Times”

  • platform: template
    friendly_name: ‘Fajr’
    value_template: ‘{{ states.sensor.prayer_times.attributes.data.timings[“Fajr”] | timestamp_custom("%H:%M") }}’
    friendly_name: ‘Dhuhr’
    value_template: ‘{{ states.sensor.prayer_times.attributes.data.timings[“Dhuhr”] | timestamp_custom("%H:%M") }}’
    friendly_name: ‘Asr’
    value_template: ‘{{ states.sensor.prayer_times.attributes.data.timings[“Asr”] | timestamp_custom("%H:%M") }}’
    friendly_name: ‘Maghrib’
    value_template: ‘{{ states.sensor.prayer_times.attributes.data.timings[“Maghrib”] | timestamp_custom("%H:%M") }}’
    friendly_name: ‘Isha’
    value_template: ‘{{ states.sensor.prayer_times.attributes.data.timings[“Isha”] | timestamp_custom("%H:%M") }}’
    friendly_name: ‘Tahajjud’
    value_template: ‘{{ states.sensor.prayer_times.attributes.data.timings[“Imsak”] | timestamp_custom("%H:%M") }}’

I am new to this but wanted to get your code to work. What do I add to the configuration.yaml

When i copied the intent is off and a lot of errors

btw. I am trying to play adhan on my android TV. I can play any media on it. However I need your sensor to for triggering the automation. Appreciate your help

I think you need to look at formatting. You cant just copy and paste.
Here is my configuration.yaml entry:

I got it finally working. Seems to formatting issues in yaml. I copied your config to the sensor.yaml file and then played around with the indent. Now to Automation and testing. Presume you have the automation running by now. I am trying to pass the media to my TV (Android ADB Command). I have 2 TV at home and they are mostly on. Need to get a speaker that can be integrated with HASS

IF you can share the automation that would be really helpful especially the template.

I am still working on that. for a HASS solution you can try mopidy. for a solution on a seperate pi or docker, try volumio.

Thanks @Gadgets, used your solution to switch over from Islamic Prayer Times to Al Adhan API. Here are my configuration files. Replace all the <use yours> in the files.


  latitude: <use yours>
  longitude: <use yours>
  elevation: <use yours>
  unit_system: <use yours>
  time_zone: <use yours>

# Configure a default setup of Home Assistant (frontend, api, etc)

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

  - platform: rest
    name: "Prayer Times"
      - data
    resource: 'http://api.aladhan.com/v1/timings?latitude=<use yours>&longitude=<use yours>&method=2&school=1'
    value_template: '{{ value_json["data"]["meta"]["method"]["name"].title() }}'
    scan_interval: 3600

  - platform: template
        friendly_name: 'Fajr'
        value_template: '{{ states("sensor.date") }} {{ states.sensor.prayer_times.attributes.data.timings["Fajr"] | timestamp_custom("%H:%M") }}'
        friendly_name: 'Sunrise'
        value_template: '{{ states("sensor.date") }} {{ states.sensor.prayer_times.attributes.data.timings["Sunrise"] | timestamp_custom("%H:%M") }}'
        friendly_name: 'Dhuhr'
        value_template: '{{ states("sensor.date") }} {{ states.sensor.prayer_times.attributes.data.timings["Dhuhr"] | timestamp_custom("%H:%M") }}'
        friendly_name: 'Asr'
        value_template: '{{ states("sensor.date") }} {{ states.sensor.prayer_times.attributes.data.timings["Asr"] | timestamp_custom("%H:%M") }}'
        friendly_name: 'Maghrib'
        value_template: '{{ states("sensor.date") }} {{ states.sensor.prayer_times.attributes.data.timings["Maghrib"] | timestamp_custom("%H:%M") }}'
        friendly_name: 'Isha'
        value_template: '{{ states("sensor.date") }} {{ states.sensor.prayer_times.attributes.data.timings["Isha"] | timestamp_custom("%H:%M") }}'
        friendly_name: 'Midnight'
        value_template: '{{ states("sensor.date") }} {{ states.sensor.prayer_times.attributes.data.timings["Midnight"] | timestamp_custom("%H:%M") }}'
       friendly_name: 'Tahajjud'
       value_template: '{{ states("sensor.date") }} {{ states.sensor.prayer_times.attributes.data.timings["Imsak"] | timestamp_custom("%H:%M") }}'
# Text to speech
  - platform: google_translate

group: !include groups.yaml
automation: !include automations.yaml
script: !include scripts.yaml


- action:
  - alias: 'Azan'
      entity_id: media_player.speaker
      media_content_id: http://praytimes.org/audio/adhan/Sunni/Adhan%20Makkah.mp3
      media_content_type: audio/mp3
    service: media_extractor.play_media
  - data:
      entity_id: media_player.speaker
      volume_level: '0.6'
    service: media_player.volume_set
  alias: Adhan
    - platform: template
      value_template: '{{ as_timestamp(strptime(states("sensor.time_date"), "%H:%M, %Y-%m-%d")) == as_timestamp(strptime(states("sensor.fajr"), "%Y-%m-%d %H:%M")) }}'
    - platform: template
      value_template: '{{ as_timestamp(strptime(states("sensor.time_date"), "%H:%M, %Y-%m-%d")) == as_timestamp(strptime(states("sensor.dhuhr"), "%Y-%m-%d %H:%M")) }}'
    - platform: template
      value_template: '{{ as_timestamp(strptime(states("sensor.time_date"), "%H:%M, %Y-%m-%d")) == as_timestamp(strptime(states("sensor.asr"), "%Y-%m-%d %H:%M")) }}'
    - platform: template
      value_template: '{{ as_timestamp(strptime(states("sensor.time_date"), "%H:%M, %Y-%m-%d")) == as_timestamp(strptime(states("sensor.maghrib"), "%Y-%m-%d %H:%M")) }}'
    - platform: template
      value_template: '{{ as_timestamp(strptime(states("sensor.time_date"), "%H:%M, %Y-%m-%d")) == as_timestamp(strptime(states("sensor.isha"), "%Y-%m-%d %H:%M")) }}'
    - platform: template
      value_template: '{{ as_timestamp(strptime(states("sensor.time_date"), "%H:%M, %Y-%m-%d")) == as_timestamp(strptime(states("sensor.tahajjud"), "%Y-%m-%d %H:%M")) }}'

- alias: "Play MP3 after 10 minutes of Maghrib Adhan"
    - platform: template
      value_template: '{{ as_timestamp(strptime(states("sensor.time_date"), "%H:%M, %Y-%m-%d")) == as_timestamp(strptime(states("sensor.maghrib"), "%Y-%m-%d %H:%M")) + 600 }}' # Add 600s=10 minutes. Subtract for before Adhan.
  - alias: ''
      entity_id: media_player.speaker
      media_content_id: <MP3 URL>
      media_content_type: audio/mp3
    service: media_extractor.play_media
  - data:
      entity_id: media_player.speaker
      volume_level: '0.6'
    service: media_player.volume_set
1 Like

thanks. this is great.

how do you add card for this player time ? in lovelace UI ?

Thanks, this was great. I was able to set up sensors with the correct time for my location.

Also for those with Echo or Amazon devices, you can install custom component HACS and install the Alexa Media Player Integration in both HACS and Home Assistant and use the following code in automations after “Azan”

  - alias: 'Azan'
      entity_id: media_player.your_echo_dot
      media_content_type: APPLE_MUSIC
      media_content_id: My playlist Adhan
    service: media_player.play_media

Note, I used APPLE_MUSIC as the service and a custom playlist named Adhan. I was not able to get Alexa service to play mp3. Alternatively you can use AMAZON_MUSIC service to play a playlist you have created on amazon music I could only find one Adhan on Amazon_Music


I set up volumio on a separate pi. then enables media player in the configuration.yaml:


i enabled discovery and the card was now available.