[Python] How to compare datetime.now() with sunrise/sunset times from Sunrise-Sunset API in...

Discussão em 'Python' iniciado por Stack, Agosto 8, 2025.

  1. Stack

    Stack Membro Participativo

    I'm working on a Python script that checks whether it's currently dark outside based on my location (Barishal, Bangladesh). I use the Sunrise-Sunset API to get sunrise and sunset times, and then compare those to datetime.now().

    import requests
    from datetime import datetime

    # My location
    MY_LAT = 22.712647
    MY_LNG = 90.351848

    parameters = {
    "lat": MY_LAT,
    "lng": MY_LNG,
    "formatted": 0 # To get ISO 8601 format for easy datetime comparison
    }

    response = requests.get("https://api.sunrise-sunset.org/json", params=parameters)
    data = response.json()

    sunrise_utc = data["results"]["sunrise"]
    sunset_utc = data["results"]["sunset"]

    # Convert strings to datetime objects
    sunrise_time = datetime.fromisoformat(sunrise_utc)
    sunset_time = datetime.fromisoformat(sunset_utc)

    # Current time
    now = datetime.utcnow()

    # Compare
    if now < sunrise_time or now > sunset_time:
    print("It's dark outside")
    else:
    print("It's daytime")



    Even though it's nighttime here, my old script was returning "It's daytime" because the sunrise/sunset times were in UTC and not adjusted to my local time.

    Continue reading...

Compartilhe esta Página