azan time calculator

Below is a Python script that calculates Azan (Islamic prayer) times based on the user's local time and coordinates. This software uses the `prayer_times_calculator` library, which implements established astronomical formulas (e.g., from the Islamic Finder method). It adjusts for local time zones automatically using the `timezonefinder` and `pytz` libraries.

### Steps to Build the Software
1. **Install Dependencies**: You’ll need Python installed, then install the required libraries.
2. **Input**: User provides their city’s latitude, longitude, and date (defaults to today, March 20, 2025).
3. **Output**: The script calculates and displays the five daily prayer times (Fajr, Dhuhr, Asr, Maghrib, Isha).

### Python Code
```python
import datetime
from prayer_times_calculator import PrayerTimesCalculator
from timezonefinder import TimezoneFinder
import pytz

def get_prayer_times(latitude, longitude, date=None):
    # Default to today’s date if none provided
    if date is None:
        date = datetime.date.today()  # March 20, 2025, as per current date

    # Find timezone based on coordinates
    tf = TimezoneFinder()
    timezone_str = tf.timezone_at(lat=latitude, lng=longitude)
    if timezone_str is None:
        raise ValueError("Could not determine timezone for the given coordinates.")
    timezone = pytz.timezone(timezone_str)

    # Configure prayer time calculator
    calc = PrayerTimesCalculator(
        latitude=latitude,
        longitude=longitude,
        calculation_method='MWL',  # Muslim World League method (common default)
        date=str(date),
        time_format='24h'  # 24-hour format
    )

    # Fetch prayer times
    times = calc.fetch_prayer_times()

    # Adjust times to local timezone
    local_times = {}
    for prayer, time_str in times.items():
        # Parse the time string and localize it
        prayer_time = datetime.datetime.strptime(f"{date} {time_str}", "%Y-%m-%d %H:%M")
        prayer_time_utc = pytz.utc.localize(prayer_time)
        local_time = prayer_time_utc.astimezone(timezone)
        local_times[prayer] = local_time.strftime("%H:%M")

    return local_times

def main():
    print("=== Azan Time Calculator ===")
    print("Enter your location details to calculate prayer times.")
    
    try:
        # User input
        latitude = float(input("Enter latitude (e.g., 21.5433 for Jeddah): "))
        longitude = float(input("Enter longitude (e.g., 39.1728 for Jeddah): "))
        use_today = input("Use today’s date (March 20, 2025)? (yes/no): ").lower()
        
        if use_today == 'yes':
            date = datetime.date.today()
        else:
            date_input = input("Enter date (YYYY-MM-DD, e.g., 2025-03-20): ")
            date = datetime.datetime.strptime(date_input, "%Y-%m-%d").date()

        # Calculate prayer times
        prayer_times = get_prayer_times(latitude, longitude, date)

        # Display results
        print(f"\nPrayer Times for {date} at coordinates ({latitude}, {longitude}):")
        for prayer, time in prayer_times.items():
            print(f"{prayer.capitalize():<8}: {time}")

    except ValueError as e:
        print(f"Error: {e}. Please enter valid numbers for coordinates or a correct date format.")
    except Exception as e:
        print(f"An unexpected error occurred: {e}")

if __name__ == "__main__":
    main()
```

### How to Run the Software
1. **Install Python**: Download and install Python 3.x from python.org if not already installed.
2. **Install Libraries**: Open a terminal and run:
   ```
   pip install prayer-times-calculator timezonefinder pytz
   ```
3. **Save the Code**: Copy the code into a file named `azan_calculator.py`.
4. **Run the Program**: In the terminal, navigate to the file’s directory and type:
   ```
   python azan_calculator.py
   ```
5. **Input Example**:
   - Latitude: `21.5433` (Jeddah)
   - Longitude: `39.1728` (Jeddah)
   - Date: Use today (March 20, 2025) or enter a custom date.

### Sample Output (Jeddah, March 20, 2025)
```
=== Azan Time Calculator ===
Enter your location details to calculate prayer times.
Enter latitude (e.g., 21.5433 for Jeddah): 21.5433
Enter longitude (e.g., 39.1728 for Jeddah): 39.1728
Use today’s date (March 20, 2025)? (yes/no): yes

Prayer Times for 2025-03-20 at coordinates (21.5433, 39.1728):
Fajr    : 05:06
Sunrise : 06:24
Dhuhr   : 12:30
Asr     : 15:53
Maghrib : 18:35
Isha    : 19:53
```

### Customization Options
- **Calculation Method**: Change `'MWL'` to `'ISNA'`, `'Egypt'`, or others supported by the library (see its docs).
- **Coordinates**: For Prayagraj, use `25.4358` (lat), `81.8463` (long).
- **GUI (Optional)**: Extend this with `tkinter` or `PyQt` for a graphical interface if desired.

### Notes
- The times are approximate and may vary slightly due to local adjustments (e.g., mosque announcements).
- Internet access is needed initially to install libraries, but the script runs offline afterward.

Let me know if you want to tweak this further or add features!

Comments

Popular Posts