Skip to content

daylight

daylight #

daylight — the stretch of a day the sun stands above some altitude.

daylight(location, around, lowest_degrees=0.0, step=timedelta(minutes=1)) #

Every step of the stretch the sun stands above lowest_degrees that holds around.

When the sun is below lowest_degrees at around, the next such stretch. lowest_degrees=0 is sunrise to sunset; -18 is first light to last.

day = cgr.scheduling.forecast.daylight(site, datetime.now(UTC))
sunrise, sunset = day[0], day[-1]

Parameters:

Name Type Description Default
location Location

Where the sun is seen from.

required
around datetime

The instant whose stretch to find; aware.

required
lowest_degrees float

The sun's altitude the stretch stays above.

0.0
step timedelta

The time between instants.

timedelta(minutes=1)

Returns:

Type Description
Array[datetime]

The stretch's instants, step apart, in the zone of around.

Raises:

Type Description
ValueError

If the sun does not cross lowest_degrees within two days of around.

Source code in capturegraph-recipes/capturegraph_recipes/scheduling/forecast/daylight.py
def daylight(
    location: cg.Location,
    around: datetime,
    lowest_degrees: float = 0.0,
    step: timedelta = timedelta(minutes=1),
) -> cg.Array[datetime]:
    """Every ``step`` of the stretch the sun stands above ``lowest_degrees`` that holds ``around``.

    When the sun is below ``lowest_degrees`` at ``around``, the next such
    stretch. ``lowest_degrees=0`` is sunrise to sunset; ``-18`` is first light
    to last.

    ```python
    day = cgr.scheduling.forecast.daylight(site, datetime.now(UTC))
    sunrise, sunset = day[0], day[-1]
    ```

    Args:
        location: Where the sun is seen from.
        around: The instant whose stretch to find; aware.
        lowest_degrees: The sun's altitude the stretch stays above.
        step: The time between instants.

    Returns:
        The stretch's instants, ``step`` apart, in the zone of ``around``.

    Raises:
        ValueError: If the sun does not cross ``lowest_degrees`` within two days
            of ``around``.
    """
    start = around - timedelta(days=1)
    instants = [start + step * index for index in range(int(timedelta(days=3) / step) + 1)]
    altitude = np.array(solar_position(location, cg.Array(instants)).altitude, dtype=np.float64)
    up = altitude > lowest_degrees
    runs = np.split(np.arange(len(instants)), np.flatnonzero(np.diff(up)) + 1)
    for run in runs[1:-1]:
        if up[run[0]] and instants[run[-1]] >= around:
            return cg.Array([instants[index] for index in run])
    raise ValueError(f"the sun does not cross {lowest_degrees:g}° within two days of {around}")