3

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?

Jean-François Corbett
  • 37,420
  • 30
  • 139
  • 188
rene
  • 101
  • 7
  • 3
    calculate the sun altitude (`Sun(observer).alt`) for the observer (positive value means the sun is up). Adjust `observer.horizon` for [different definitions of dusk/dawn (twilight)](http://rhodesmill.org/pyephem/rise-set.html#computing-twilight). – jfs Oct 22 '14 at 07:07
  • 1
    `if now > sunrise && now < sunset`? – Jean-François Corbett Oct 22 '14 at 08:20
  • Thanks for the suggestion, this is probably the solution, need to do some tesitng stiil. if datetime.now() > previous_rising and datetime.now() < next_setting – rene Oct 22 '14 at 09:12
  • `datetime.now()` is the wrong function. Either use `datetime.utcnow()` or `ephem.now()`. You could write `a < x < b` in Python. `ephem` itself uses something like this internally: `is_up = lambda sun=Sun(observer): (sun.alt + sun.radius - observer.horizon) > 0` – jfs Oct 25 '14 at 03:52

1 Answers1

7

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
Brandon Rhodes
  • 83,755
  • 16
  • 106
  • 147
  • Thanks for the explanation, very useful and clear. The only thing I don't get yet is the -12 value in the twilight formula. Can you explain this? – rene Oct 29 '14 at 07:52
  • 2
    One of the USNO definitions of twilight is when the sun is twelve degrees below the horizon. – Brandon Rhodes Oct 30 '14 at 17:53