def seconds_till_daytime(lat,lon,delta_minutes): if is_it_daytime(lat,lon,delta_minutes): return 0 now = datetime.now(UTC()) astral = Astral() sunrise = astral.sunrise_utc(now,lat,lon) + timedelta(minutes=delta_minutes) if sunrise < now: sunrise = astral.sunrise_utc(now + timedelta(hours=23),lat,lon) + timedelta(minutes=delta_minutes) return int((sunrise-now).total_seconds())+1
def draw_astronomical(city_name, geo_data): datetime_day_start = datetime.datetime.now().replace(hour=0, minute=0, second=0, microsecond=0) a = Astral() a.solar_depression = 'civil' city = Location() city.latitude = geo_data["latitude"] city.longitude = geo_data["longitude"] city.timezone = geo_data["timezone"] answer = "" moon_line = "" for time_interval in range(72): current_date = (datetime_day_start + datetime.timedelta(hours=1 * time_interval)).replace( tzinfo=pytz.timezone(geo_data["timezone"])) sun = city.sun(date=current_date, local=False) dawn = sun['dawn'] # .replace(tzinfo=None) dusk = sun['dusk'] # .replace(tzinfo=None) sunrise = sun['sunrise'] # .replace(tzinfo=None) sunset = sun['sunset'] # .replace(tzinfo=None) if current_date < dawn: char = " " elif current_date > dusk: char = " " elif dawn < current_date and current_date < sunrise: char = u"─" elif sunset < current_date and current_date < dusk: char = u"─" elif sunrise < current_date and current_date < sunset: char = u"━" answer += char # moon if time_interval % 3 == 0: moon_phase = city.moon_phase( date=datetime_day_start + datetime.timedelta(hours=time_interval)) moon_phase_emoji = constants.MOON_PHASES[ int(math.floor(moon_phase * 1.0 / 28.0 * 8 + 0.5)) % len(constants.MOON_PHASES)] if time_interval in [0, 24, 48, 69]: moon_line += moon_phase_emoji + " " else: moon_line += " " answer = moon_line + "\n" + answer + "\n" answer += "\n" return answer
def render_moonphase(_, query): """ A symbol describing the phase of the moon """ astral = Astral() moon_index = int( int(32.0 * astral.moon_phase(date=datetime.datetime.today()) / 28 + 2) % 32 / 4) return MOON_PHASES[moon_index]
def test_track_sunrise(self): """Test track the sunrise.""" latitude = 32.87336 longitude = 117.22743 # Setup sun component self.hass.config.latitude = latitude self.hass.config.longitude = longitude setup_component(self.hass, sun.DOMAIN, {sun.DOMAIN: { sun.CONF_ELEVATION: 0 }}) # Get next sunrise/sunset astral = Astral() utc_now = dt_util.utcnow() mod = -1 while True: next_rising = (astral.sunrise_utc(utc_now + timedelta(days=mod), latitude, longitude)) if next_rising > utc_now: break mod += 1 # Track sunrise runs = [] unsub = track_sunrise(self.hass, lambda: runs.append(1)) offset_runs = [] offset = timedelta(minutes=30) unsub2 = track_sunrise(self.hass, lambda: offset_runs.append(1), offset) # run tests self._send_time_changed(next_rising - offset) self.hass.block_till_done() self.assertEqual(0, len(runs)) self.assertEqual(0, len(offset_runs)) self._send_time_changed(next_rising) self.hass.block_till_done() self.assertEqual(1, len(runs)) self.assertEqual(0, len(offset_runs)) self._send_time_changed(next_rising + offset) self.hass.block_till_done() self.assertEqual(2, len(runs)) self.assertEqual(1, len(offset_runs)) unsub() unsub2() self._send_time_changed(next_rising + offset) self.hass.block_till_done() self.assertEqual(2, len(runs)) self.assertEqual(1, len(offset_runs))
def sunrise_time(): from astral import Astral astr_object = Astral() astr_object.solar_depression = "civil" try: return astr_object[CITY].sun(local=True)["sunrise"] except Exception as error: ErrorWriter.write_error(error) return None
def __init__(self, city_name=default_city_name): if VERSION == 2: self._city = lookup("Amsterdam", database()) self._sun = self.sun(datetime.now()) else: self._a = Astral() self._a.solar_depression = 'civil' self._city = self._a[city_name] self._timezone = pytz.timezone(self._city.timezone)
def render_sunset(data, query): location = data['location'] city_name = location astral = Astral() location = Location( ('Nuremberg', 'Germany', 49.453872, 11.077298, 'Europe/Berlin', 0)) sun = location.sun(date=datetime.datetime.today(), local=True) return str(sun['sunset'])
def test_Astral_TimeAtElevation_SunRising(): a = Astral() l = a['London'] d = datetime.date(2016, 1, 4) dt = a.time_at_elevation_utc(6, SUN_RISING, d, l.latitude, l.longitude) cdt = datetime.datetime(2016, 1, 4, 9, 5, 0, tzinfo=pytz.UTC) # Use error of 5 minutes as website has a rather coarse accuracy assert datetime_almost_equal(dt, cdt, 300)
def sun(request): """ Return sunrise, sunset etc. times. """ a = Astral() a.solar_depression = 'civil' l = Location() # l.name = 'Lapinlahden sairaala' # l.region = 'Helsinki' lat = request.GET.get('lat') lon = request.GET.get('lon') if lat is None or lon is None: l.latitude = 60.167761 l.longitude = 24.9118141 l.loc_source = 'default' else: l.latitude = float(lat) l.longitude = float(lon) l.loc_source = 'request' l.timezone = 'UTC' l.elevation = 0 timeformat = request.GET.get('timeformat', 'epoch') date_str = request.GET.get('date') format_str = request.GET.get('format', 'json') date = datetime.datetime.now().date() if date_str is not None: date = parse(date_str).date() pass sundata = { 'now': datetime.datetime.now(tz=pytz.UTC), # .astimezone(pytz.UTC), 'date': date.strftime('%Y-%m-%d'), 'lat': l.latitude, 'lon': l.longitude, 'loc_source': l.loc_source, } try: sun = l.sun(date=date, local=False) except AstralError as e: return HttpResponse(json.dumps({'error': str(e)}), content_type='application/json') for k in ['dawn', 'sunrise', 'noon', 'sunset', 'dusk']: sundata[k] = sun[k] if timeformat == 'iso': for k in sundata.keys(): if isinstance(sundata[k], datetime.datetime): sundata[k] = sundata[k].isoformat() else: # timeformat == 'epoch': for k in sundata.keys(): if isinstance(sundata[k], datetime.datetime): sundata[k] = int(sundata[k].timestamp()) res_str = json.dumps(sundata, indent=2) return HttpResponse(res_str, content_type='application/json')
def get_sun(): a = Astral() a.solar_depression = 'civil' city = a['Helsinki'] sun = city.sun(date=datetime.now(), local=True) sunset = sun['dusk'] sun = city.sun(date=datetime.now() + timedelta(days=1), local=True) sunrise = sun['dawn'] return sunrise, sunset
def test_Astral_JulianDay_DateTime(): a = Astral() dt = datetime.datetime(2015, 1, 1, 1, 36, 0) jd = a._julianday(dt) assert float_almost_equal(jd, 2457023.57, 0.1) dt = datetime.datetime(2015, 1, 1, 15, 12, 0) jd = a._julianday(dt) assert float_almost_equal(jd, 2457024.13, 0.1)
def test_Astral_Nighttime(): a = Astral() l = a['London'] d = datetime.date(2016, 1, 6) start, end = a.night_utc(d, l.latitude, l.longitude) cstart = datetime.datetime(2016, 1, 6, 18, 10, 0, tzinfo=pytz.UTC) cend = datetime.datetime(2016, 1, 7, 6, 2, 0, tzinfo=pytz.UTC) assert datetime_almost_equal(start, cstart, 300) assert datetime_almost_equal(end, cend, 300)
def SetSunTimes(): cityName = "London" a = Astral() a.solar_depression = "civil" city = a[cityName] sun = city.sun(date=datetime.now(), local=True) variables.Set("dawn", str(sun['dawn'].strftime("%H:%M"))) variables.Set("sunrise", str(sun['sunrise'].strftime("%H:%M"))) variables.Set("sunset", str(sun['sunset'].strftime("%H:%M"))) variables.Set("dusk", str(sun['dusk'].strftime("%H:%M")))
def test_Astral_JulianDay_DateTimeZone(): a = Astral() dt = datetime.datetime(2015, 1, 1, 1, 36, 0) jd = a._julianday(dt, 1) assert float_almost_equal(jd, 2457023.51, 0.1) dt = datetime.datetime(2015, 10, 10, 1, 36, 0) jd = a._julianday(dt, 5) assert float_almost_equal(jd, 2457305.36, 0.1)
def is_it_night(): # TODO: cache result for swift result a = Astral() city_name = 'Oslo' city = a[city_name] sun = city.sun(local=True) sunrise = sun['sunrise'] dusk = sun['dusk'] now = datetime.now(timezone('CET')) return now < sunrise or now > dusk
def sun_api(): data = {} city_name = 'Denver' a = Astral() a.solar_depression = 'civil' city = a[city_name] sun = city.sun(date=dt.datetime.today(), local=True) data = {k: sun[k].hour * 60 + sun[k].minute for k in sun} data['moon_phase'] = city.moon_phase() return data
def auto(self, action: str = 'on', sun_state: str = 'sunset', offset: int = 0): a = Astral() a.solar_depression = 'civil' city = a[settings.LOCATION] sun = city.sun(date=datetime.now(), local=True) if datetime.now(sun[sun_state].tzinfo) >= sun[sun_state] + timedelta( seconds=offset): {'on': self.on, 'off': self.off}[action]()
def initAstral(self): a = Astral() a.solar_depression = 'civil' l = Location() l.name = 'Dolbeau-Mistassini' l.region = 'Canada' l.latitude = 48.9016 l.longitude = -72.2156 l.timezone = 'America/Montreal' l.elevation = 139 self.location = l
def isDay(DATETIME): """Returns 1 if the given time is the day time""" a = Astral() city = a['Seattle'] sun = city.sun(date=DATETIME) if ((DATETIME.hour > sun['sunrise'].hour) & (DATETIME.hour < sun['sunset'].hour)): return 1 else: return 0
def check_if_dark(): from astral import Astral city_name = 'Kiev' a = Astral() a.solar_depression = 'civil' city = a[city_name] sun = city.sun(date=datetime.datetime.now(), local=True) T = datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=2))) if (sun['sunrise'] < T < sun['sunset']): return False return True
def SunUpDown(location): a = Astral() a.solar_depression = 'civil' timezone = location.timezone Now = strftime("%H:%M", localtime()) dt = datetime.datetime.fromtimestamp(time.mktime(localtime())) tz = pytz.timezone("Europe/Berlin") dtn = tz.localize(dt) dtnT = dtn + datetime.timedelta(days=1) sun = location.sun(dtn, local=True) sunT = location.sun(dtnT, local=True) if (sun['sunrise'].hour < 10): Sunrise = '0' + str(sun['sunrise'].hour) + ':' else: Sunrise = str(sun['sunrise'].hour) + ':' if (sun['sunrise'].minute < 10): Sunrise = Sunrise + '0' + str(sun['sunrise'].minute) else: Sunrise = Sunrise + str(sun['sunrise'].minute) if (sunT['sunrise'].hour < 10): SunriseT = '0' + str(sunT['sunrise'].hour) + ':' else: SunriseT = str(sunT['sunrise'].hour) + ':' if (sunT['sunrise'].minute < 10): SunriseT = SunriseT + '0' + str(sunT['sunrise'].minute) else: SunriseT = SunriseT + str(sunT['sunrise'].minute) if (sun['sunset'].hour < 10): Sunset = '0' + str(sun['sunset'].hour) + ':' else: Sunset = str(sun['sunset'].hour) + ':' if (sun['sunset'].minute < 10): Sunset = Sunset + '0' + str(sun['sunset'].minute) else: Sunset = Sunset + str(sun['sunset'].minute) if (sunT['sunset'].hour < 10): SunsetT = '0' + str(sunT['sunset'].hour) + ':' else: SunsetT = str(sunT['sunset'].hour) + ':' if (sunT['sunset'].minute < 10): SunsetT = SunsetT + '0' + str(sunT['sunset'].minute) else: SunsetT = SunsetT + str(sunT['sunset'].minute) ''' print sun['sunrise'], sun['sunset'] print print sunT['sunrise'], sunT['sunset'] print '-------------' ''' return Sunrise, Sunset, SunriseT, SunsetT, sun['sunrise'], sun['sunset'], ( (dtn > sun['sunrise']) and (dtn < sun['sunset']))
def sunyears(start_year, end_year): city_name = 'London' a = Astral() a.solar_depression = 'civil' city = a[city_name] sun_times = {} print('Information for %s/%s\n' % (city_name, city.region)) timezone = city.timezone print('Timezone: %s' % timezone) print(' Latitude: %.02f; Longitude: %.02f\n' % (city.latitude, city.longitude)) delta = datetime.timedelta(days=1) for year in range(start_year, end_year + 1): # Loop through all days in year start_date = datetime.date(year, 1, 1) end_date = datetime.date(year, 12, 31) d = start_date while d <= end_date: sun = city.sun(d, local=True) # print('Dawn: %s' % str(sun['dawn'])) # print('Sunrise: %s' % str(sun['sunrise'])) # print('Noon: %s' % str(sun['noon'])) # print('Sunset: %s' % str(sun['sunset'])) # print('Dusk: %s' % str(sun['dusk'])) # pprint(sun) sun_times[json_serial(d)] = sun # print(json.dumps(sun_times, default=json_serial, # indent=4, sort_keys=True)) d += delta # print(json.dumps(sun_times, default=json_serial)) outfilename = "suntimes-{}-{}".format(start_year, end_year) outfilename = os.path.join("data", outfilename) mkdir("data") with open(outfilename + ".json", "w") as outfile: json.dump(sun_times, outfile, default=json_serial, indent=4, separators=(',', ': '), sort_keys=True) with open(outfilename + ".min.json", "w") as outfile: json.dump(sun_times, outfile, default=json_serial)
def setup_location(): global city city_name = 'Bucharest' a = Astral() a.solar_depression = 'civil' city = a[city_name] print('Solar data for %s/%s\n' % (city_name, city.region)) timezone = city.timezone print('Timezone: %s' % timezone)
def __init__(self): city_name = config.get('ASTRA_CITY') a = Astral() a.solar_depression = 'civil' self.__city = a[city_name] self.__today = None self.__sun = None self.__mode = None self.__timezone = pytz.timezone(self.__city.timezone) self.is_day()
def test_Astral(): location_name = 'Jubail' dd = Astral() dd.solar_depression = 'civil' location = dd[location_name] assert location.timezone == 'Asia/Riyadh' sun = location.sun() sunrise = location.sunrise(local=True) assert sunrise == sun['sunrise']
def test_EquationOfTime(): a = Astral() dt = datetime.datetime(2015, 10, 10, 0, 54, 0) jc = a._jday_to_jcentury(a._julianday(dt, -4)) etime = a._eq_of_time(jc) assert float_almost_equal(etime, 12.84030157, 0.0001) dt = datetime.datetime(2017, 1, 1, 2, 0, 0) jc = a._jday_to_jcentury(a._julianday(dt, 2)) etime = a._eq_of_time(jc) assert float_almost_equal(etime, -3.438084536, 0.0001)
def test_GeomMeanLongSun(): a = Astral() dt = datetime.datetime(2015, 10, 10, 1, 36, 0) jc = a._jday_to_jcentury(a._julianday(dt, 5)) geom = a._geom_mean_long_sun(jc) assert float_almost_equal(geom, 198.1484524, 0.1) dt = datetime.datetime(2015, 1, 1, 1, 36, 0) jc = a._jday_to_jcentury(a._julianday(dt, -4)) geom = a._geom_mean_long_sun(jc) assert float_almost_equal(geom, 280.5655139, 0.1)
def test_Astral_SolarAzimuth(): a = Astral() l = a['London'] test_data = { datetime.datetime(2015, 12, 14, 11, 0, 0, tzinfo=pytz.UTC): 167, datetime.datetime(2015, 12, 14, 20, 1, 0): 279, } for dt, angle1 in test_data.items(): angle2 = a.solar_azimuth(dt, l.latitude, l.longitude) assert float_almost_equal(angle1, angle2)
def get_light_state(self): astral = Astral() astral.solar_depression = "civil" astral_city = astral["Perth"] now = datetime.datetime.now(pytz.timezone('Australia/Perth')) astral_city_sun = astral_city.sun(date=now, local=True) if (astral_city_sun['sunrise'] - datetime.timedelta(hours=1)) < now < astral_city_sun['sunset']: return "daylight" elif 1 <= now.hour <= 5: return "witching" else: return "evening"
def test_Location_TimeAtElevation(): dd = Astral() location = dd['New Delhi'] test_data = { datetime.date(2016, 1, 5): datetime.datetime(2016, 1, 5, 10, 0), } for day, cdt in test_data.items(): cdt = location.tz.localize(cdt) dt = location.time_at_elevation(28, date=day) assert datetime_almost_equal(dt, cdt, seconds=600)