<p>你可以像我一样,使用这个公共域<a href="http://web.archive.org/web/20130120173224/http://www.kortis.to/radix/python/code/Sun.py" rel="nofollow noreferrer">Sun.py</a>模块来计算太阳相对于地球位置的位置。它很旧,但多年来对我很管用。我对它做了一些表面上的修改,使之更能适应Python2.7的最新版本,比如使其中的几个类成为新样式,但在大多数情况下它没有改变。在</p>
<p>这是我创建的一个模块,名为日出集.py,它展示了如何使用它来计算给定地理坐标和时区的特定位置的日出和日落时间。引用的<code>timezone</code>模块是<code>datetime</code>模块文档中描述的<a href="http://docs.python.org/2/library/datetime.html?highlight=tzinfo#datetime.tzinfo" rel="nofollow noreferrer">^{<cd2>}</a>抽象基类的实现。在</p>
<pre><code># -*- coding: iso-8859-1 -*-
import datetime
import timezone # concrete tzinfo subclass based on the Python docs
import math
from Sun import Sun
__all__ = ['getsuninfo', 'Place']
class Place(object):
def __init__(self, name, coords, tz=timezone.Pacific):
self.name = name # string
self.coords = coords # tuple (E/W long, N/S lat)
self.tz = tz # tzinfo constant
def _hoursmins(hours):
"""Convert floating point decimal time in hours to integer hrs,mins"""
frac,h = math.modf(hours)
m = round(frac*60, 0)
if m == 60: # rounded up to next hour
h += 1; m = 0
return int(h),int(m)
def _ymd(date):
"""Return y,m,d from datetime object as tuple"""
return date.timetuple()[:3]
def getsuninfo(location, date=None):
"""Return local datetime of sunrise, sunset, and length of day in hrs,mins)"""
if date == None:
querydate = datetime.date.today()
else: # date given should be datetime instance
querydate = date
args = _ymd(querydate) + location.coords
utcrise, utcset = Sun().sunRiseSet(*args)
daylength = Sun().dayLength(*args)
hrs,mins = _hoursmins(daylength)
risehour, risemin = _hoursmins(utcrise)
sethour, setmin = _hoursmins(utcset)
# convert times to timedelta values (ie from midnight utc of the date)
midnight = datetime.datetime(tzinfo=timezone.utc, *_ymd(querydate))
deltarise = datetime.timedelta(hours=risehour, minutes=risemin)
utcdatetimerise = midnight+deltarise
deltaset = datetime.timedelta(hours=sethour, minutes=setmin)
utcdatetimeset = midnight+deltaset
# convert results from UTC time to local time of location
localrise = utcdatetimerise.astimezone(location.tz)
localset = utcdatetimeset.astimezone(location.tz)
return localrise, localset, hrs, mins
if __name__ == "__main__":
import datetime, timezone
def unittest(location, testdate):
risetime, settime, hrs, mins = getsuninfo(location, testdate)
print "Location:", location.name
print "Date:", testdate.strftime("%a %x")
print risetime.strftime("Sunrise %I:%M %p"), settime.strftime("- Sunset %I:%M %p (%Z)")
print "daylight: %d:%02d" % (hrs,mins)
print
place = Place("My House", (-121.990278, 47.204444), timezone.Pacific)
# test dates just before and after DST transitions
print "pre 2007"
print "========="
unittest(place, datetime.date(2006, 4, 1))
unittest(place, datetime.date(2006, 4, 2))
unittest(place, datetime.date(2006, 10, 28))
unittest(place, datetime.date(2006, 10, 29))
print "2007"
print "========="
unittest(place, datetime.date(2007, 3, 10))
unittest(place, datetime.date(2007, 3, 11))
unittest(place, datetime.date(2007, 11, 3))
unittest(place, datetime.date(2007, 11, 4))
</code></pre>