Python 中的日出和日落时间

新手上路,请多包涵

我目前正在从事一个项目,该项目在触发与光相关的某些活动时通知用户。我已经完成了与光相关的部分。因此,我需要找到一种在 python 中检索日出和日落时间的有效方法,因为整个脚本都是用 python 编写的。我知道有几个其他语言的库,我想知道在 python 中最方便的方法是什么。

它看起来很像这样,我想:

 if(sunrise<T<sunset) and (light<threshold):
    notifyUser()

我会很感激这里的任何帮助,祝你好运。

原文由 bkaankuguoglu 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1k
2 个回答

我比较了几个包( suntimesuntimessunrietastral )和他们返回的日出和日落时间。他们都返回当地时间,但您也可以轻松获得 UTC 时间。这是结果:

 from datetime import date, datetime, timezone, timedelta
import pytz
import time
from suntime import Sun, SunTimeException
from suntimes import SunTimes
import sunriset
import astral, astral.sun

latitude = 52.0691667
longitude = 19.4805556
altitude = 0
tz_poland = pytz.timezone('Europe/Warsaw')
tz_name = 'Europe/Warsaw'
for_date = date(2021, 4, 6)
print('====== suntime ======')
abd = for_date
sun = Sun(latitude, longitude)
today_sr = sun.get_sunrise_time()
today_ss = sun.get_sunset_time()
print(today_sr.astimezone(tz_poland))
print(today_ss.astimezone(tz_poland))
print('====== suntimes ======')
sun2 = SunTimes(longitude=longitude, latitude=latitude, altitude=altitude)
day = datetime(for_date.year, for_date.month, for_date.day)
print(sun2.risewhere(day, tz_name))
print(sun2.setwhere(day, tz_name))
print('====== sunriset ======')
local = datetime.now()
utc = datetime.utcnow()
local_tz = float(((local - utc).days * 86400 + round((local - utc).seconds, -1))/3600)
number_of_years = 1
start_date = for_date
df = sunriset.to_pandas(start_date, latitude, longitude, 2, number_of_years)
for index, row in df.iterrows():
    print(row['Sunrise'])
    print(row['Sunset'])
    break
print('====== astral ======')
l = astral.LocationInfo('Custom Name', 'My Region', tz_name, latitude, longitude)
s = astral.sun.sun(l.observer, date=for_date)
print(s['sunrise'].astimezone(tz_poland))
print(s['sunset'].astimezone(tz_poland))

和回报:

 ====== suntime ======
2021-04-06 06:05:00+02:00
2021-04-06 19:16:00+02:00
====== suntimes ======
2021-04-06 06:04:34.000553+02:00
2021-04-06 19:17:16.000613+02:00
====== sunriset ======
0 days 06:02:52.093465
0 days 19:16:49.892350
====== astral ======
2021-04-06 06:03:39.792229+02:00
2021-04-06 19:17:01.188463+02:00

请注意只有 suntimes 包支持高度。

原文由 Wojciech Jakubas 发布,翻译遵循 CC BY-SA 4.0 许可协议

检查 星体。这是 他们文档中的一个稍微修改过的示例

 >>> from astral import Astral
>>> city_name = 'London'
>>> a = Astral()
>>> a.solar_depression = 'civil'
>>> city = a[city_name]
>>> sun = city.sun(date=datetime.date(2009, 4, 22), local=True)

>>> if (sun['sunrise'] < T < sun['sunset']) and (light < threshold):
>>>    notifyUser()

如果您使用类似此示例的内容,请记住将 city_name 和提供的日期更改为 city.sun

原文由 Kevin London 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题