Given the latitude and longitude, how can I tell if it's daylight?
I'm writing a Python program that needs to determine whether it's post-sunrise or not, given only the current UTC time and the target latitude and longitude. I开发者_JAVA技巧 see apps do this sort of thing all the time, but I have no idea how it's done. Any ideas?
Here's someone's implementation of sunrise/sunset calculation in Python: http://michelanders.blogspot.com/2010/12/calulating-sunrise-and-sunset-in-python.html
A complete layout of the algorithm is here
Not a lot to add really. The 10 points in the document quoted break it down into simple to reproduce steps that can be implemented in any language really.
Just doing a quick google search I found this. The calculations in the NOAA Sunrise/Sunset and Solar Position Calculators are based on equations from Astronomical Algorithms, by Jean Meeus. The sunrise and sunset results have been verified to be accurate to within a minute for locations between +/- 72° latitude, and within 10 minutes outside of those latitudes.
A detailed explanation of the calculation details can be found from that page and also here.
You need something that just works™? Use the superior language. And you know it'll always work. How can you trust 122 lines of advanced astrophysics? You can't. But you can always trust PHP.
>>> def is_day(lat, lon): # optinally adjust zenith (currently 96) at the end of the line
... return subprocess.check_output(["php","-r","""date_default_timezone_set("GMT");\n$a=date_sunrise(time(),SUNFUNCS_RET_DOUBLE,{0},{1},{2},0);\n$b=date_sunset(time(),SUNFUNCS_RET_DOUBLE,{0},{1},{2},0);\n$t=date("H")+date("i")/60+date("s")/3600;\necho($a<$b?($t>$a&&$t<$b):($t>$a||$t<$b))?"day":"night";""".format(lat,lon,96)])=="day"
... # ^^ optionally adjust zenith here
...
>>> is_day(-33,151) # Sydney
True
>>> is_day(0,0) # Some hundred km off the coast of Africa
False
>>> __import__("datetime").datetime.utcnow()
datetime.datetime(2012, 2, 10, 22, 29, 30, 365019)
>>>
精彩评论