Search code examples
pythonlightpyephem

How to determine if it is daytime (light outside?) in python using ephem library


The ephem python library can perfectly determine the next sunrise and sunset.

What I want to know is if it is light outside or not at a certain moment in time. Is there a simple function call in ephem that returns this?


Solution

  • Organizations like the United States Naval Observatory have definitions for “it is light outside” — you can find the USNO’s definitions here:

    http://aa.usno.navy.mil/faq/docs/RST_defs.php

    Once you choose the definition you want, ask the Sun object for its alt and compare that value with the altitude in the definition from the USNO. I strongly recommend that you use the alt, as it is fast for PyEphem to compute. If instead you ask about the sunrise and sunset, then you sent PyEphem off on a very expensive iterative search where it has to keep trying different times of day until it finally discovers the moment of sunrise and sunset — which you are really not interested in, it sounds like. You just want to compare the Sun's altitude to your own threshold for “is it light outside.”

    Note that alt will be in radians, so you will need to convert your chosen number of degrees before comparing:

    import ephem

    s = ephem.Sun()
    sf = ephem.city('San Francisco')
    s.compute(sf)
    twilight = -12 * ephem.degree
    print 'Is it light in SF?', s.alt > twilight