如何在 Python 中使用 skyfield 计算日出和日落
以下代码将使用 skyfield 库计算特定位置和海拔的日出和日落。注意你需要下载 de413.bsp。
sunrise_sunset.py
from skyfield import api
from skyfield import almanac
from datetime import datetime
from datetime import timedelta
import dateutil.parser
from calendar import monthrange
ts = api.load.timescale()
ephem = api.load_file('de413.bsp')
def compute_sunrise_sunset(location, year=2019, month=1, day=1):
t0 = ts.utc(year, month, day, 0)
# t1 = t0 加一天
t1 = ts.utc(t0.utc_datetime() + timedelta(days=1))
t, y = almanac.find_discrete(t0, t1, almanac.sunrise_sunset(ephem, location))
sunrise = None
for time, is_sunrise in zip(t, y):
if is_sunrise:
sunrise = dateutil.parser.parse(time.utc_iso())
else:
sunset = dateutil.parser.parse(time.utc_iso())
return sunrise, sunset
# 计算慕尼黑附近随机位置的日出和日落
location = api.Topos('48.324777 N', '11.405610 E', elevation_m=519)
now = datetime.now()
sunrise, sunset = compute_sunrise_sunset(location, now.year, now.month, now.day)
# 打印结果(示例)
print(f'Sunrise today: {sunrise}')
print(f'Sunset today: {sunset}')此上下文中日出和日落的定义
According to the skyfield documentation:
sunrise_definition.txt
Skyfield uses the same definition as the United States Naval Observatory: the Sun is up when its center is 0.8333 degrees below the horizon, which accounts for both its apparent radius of around 16 arcminutes and also for the 34 arcminutes by which atmospheric refraction on average lifts the image of the Sun.其他注意事项
- 注意此模型不考虑山脉等障碍物
- 注意生成的时间戳是 UTC,如果你想要本地时间,你需要适当转换它们
示例输出:
sunrise_example_output.txt
Sunrise today: 2022-06-19 03:12:56+00:00
Sunset today: 2022-06-19 19:18:38+00:00If this post helped you, please consider buying me a coffee or donating via PayPal to support research & publishing of new posts on TechOverflow