def night_p(nvec, dt): l = astral.LocationInfo("", "", "UTC", *to_latlong(nvec)) try: sunrise, sunset = astral.sun.daylight(l.observer, dt.date()) #astral gives sunset on the day, and previous sunrise, so adjust if reqd if sunrise.date() != dt.date(): sunrise = astral.sun.sunrise( l.observer, (dt + datetime.timedelta(days=1)).date()) #replace with timezone naive versions sunrise = sunrise.replace(tzinfo=None) sunset = sunset.replace(tzinfo=None) if (sunset > sunrise): #..dark..sr..light..ss..dark if (dt >= sunrise - datetime.timedelta(minutes=30) and dt <= sunset + datetime.timedelta(minutes=30)): return False else: #..light..ss..dark..sr..light if (dt <= sunset + datetime.timedelta(minutes=30) or dt >= sunrise - datetime.timedelta(minutes=30)): return False except ValueError as e: #daylight raises value error if no sunrise/sunset #summer in northern hemisphere, assume midday sun if nvec[2] > 0 and dt.month >= 4 and dt.month <= 8: return False #and for summer in southern hemisphere southern... if nvec[2] < 0 and dt.month in (10, 11, 12, 1, 2): return False return True
def updateSunMoon(self): # print('updateSunMoon') try: (lat, lon) = parseDMSString(self.coordLineEdit.text().strip()) except Exception: self.clearSun() return locl = astral.LocationInfo('', '', '', lat, lon) dt = self.getLocalDateTime() try: if self.displaySunUtcCheckBox.isChecked(): s = sun(locl.observer, date=dt, tzinfo=pytz.utc) else: s = sun(locl.observer, date=dt, tzinfo=dt.tzinfo) except Exception: self.clearSun() return msg = [] if self.displaySunUtcCheckBox.isChecked(): fmt = '%Y-%m-%dT%H:%M:%SZ' else: fmt = '%Y-%m-%dT%H:%M:%S%z' for k, v in s.items(): msg.append('{:>7}, {}'.format(k, v.strftime(fmt))) sunstr = '\n'.join(msg) self.sunTextEdit.clear() self.sunTextEdit.insertPlainText(sunstr) azimuth = astral.sun.azimuth(locl.observer, dt) elev = astral.sun.elevation(locl.observer, dt) self.sunAzimuthLineEdit.setText('{:.8f}'.format(azimuth)) self.sunElevationLineEdit.setText('{:.8f}'.format(elev))
def func(self): """Show server time data in a table.""" lat, lon, ele = 33.43, -112.07, 24 here = self.character.location if here: x = float(here.tags.get(category="coordx", default=0)) y = float(here.tags.get(category="coordy", default=0)) # z = here.tags.get(category="coordz") if x and y: lat, lon = float(y/10000), float(x/10000) print('Using location coordinates: {}, {}'.format(lat, lon)) place = astral.LocationInfo(timezone='UTC', latitude=lat, longitude=lon) obsr = astral.Observer(latitude=lat, longitude=lon, elevation=ele) def time_dif(at, when): diff = abs(at - when) return 'now' if diff.total_seconds() < 60 else (utils.time_format(diff.total_seconds(), 2) + (' ago' if at > when else '')) def moon_phase(days): """ Summarize the visible portion, given days into cycle Args: days (int or float): days into current cycle Returns: phase (str): summary of view of visible portion """ phases = ('new', 'waxing crescent', 'First quarter', 'waxing gibbous', 'full', 'waning gibbous', 'last quarter', 'waning crescent') percent = float((float(days) + 0.5) / 29.53) phase = int((percent - int(percent)) * len(phases)) return phases[phase] try: sun = astral.sun.sun(date=datetime.date.today(), observer=obsr) except Exception as e: return else: past = here.tags.get('past', category='realm') moon = astral.moon.phase(date=datetime.date.today()) now = timezone.now() moment = ['dawn', 'sunrise', 'noon', 'sunset', 'dusk'] events = zip([each.capitalize() + ':' for each in moment], [time_dif(now, sun[each]) for each in moment]) table1 = EvTable("|wServer", '|wtime', align='l', width=75) table1.add_row('Current uptime', utils.time_format(gametime.uptime(), 3)) table1.add_row('First start', time_dif(datetime.datetime.now(), datetime.datetime.fromtimestamp(gametime.server_epoch()))) if here.tags.get('past', category='realm'): table1.add_row('Moon phase', moon_phase(moon)) table1.reformat_column(0, width=20) up = self.cmdstring == 'uptime' # User asking for uptime mode self.msg(('Current uptime: ' + utils.time_format(gametime.uptime(), 3)) if up else str(table1)) if past: # Astral events are to be displayed while in past realm table2 = EvTable("|wEvent", "|wTime until", align="l", width=75) for entry in events: table2.add_row(entry[0], entry[1]) table2.reformat_column(0, width=20) self.msg(str(table2) if self.cmdstring == 'events' else ('\n' + str(table2)))
def get_sun_time(): ''' 获取真正的太阳时,待完成,需要地址的GPS的定位 :return: ''' location_XiChong = astral.LocationInfo('Shijiazhuang', 'China', 'Asia/Shanghai', 34.16, 108.91) print(location_XiChong.timezone) s = sun(location_XiChong.observer, date=datetime.date(1987, 6, 18)) print(s.get("noon")) print(s)
def on_all_values_set(self): tz = tzlocal.get_localzone() tz_name = str(tz) log.debug(f'Local Timezone: {tz_name}') # unsure why we need the location in 2.1 self._astral_location = _astral.LocationInfo(name='HABApp', ) self._astral_location.latitude = self.latitude self._astral_location.longitude = self.longitude self._astral_location.timezone = tz_name self.astral_observer = self._astral_location.observer self.astral_observer.elevation = self.elevation
def sunset(h): sunset_trigger_active = False while True: if sunset_trigger_active: trigger_sunset(h) sunset_trigger_active = False # city = lookup("Hamburg", database()) city = astral.LocationInfo("Hamburg", "Germany", "Europe/Berlin", 53.551086, 9.993682) print(( f"Information for {city.name}/{city.region}\n" f"Timezone: {city.timezone}\n" f"Latitude: {city.latitude:.02f}; Longitude: {city.longitude:.02f}\n" )) s = sun(city.observer, date=datetime.today()) print((f'Dawn: {s["dawn"]}\n' f'Sunrise: {s["sunrise"]}\n' f'Noon: {s["noon"]}\n' f'Sunset: {s["sunset"]}\n' f'Dusk: {s["dusk"]}\n')) delta = s["sunset"] - datetime.now( timezone.utc) - timedelta(seconds=offset) delta_s = delta.total_seconds() if (delta_s <= 0.0): print('Last sunset trigger was:', abs(delta_s), 'seconds ago') trigger_point = seconds_in_a_day + delta_s print('Next scheduld sunset trigger in:', trigger_point, 'seconds.') else: trigger_point = delta_s print('Next scheduld sunset trigger in:', trigger_point, 'seconds.') if trigger_point > seconds_per_hour: print("Sleep for", seconds_per_hour, 'seconds.') time.sleep(seconds_per_hour) else: print('Programming trigger, sleep for', trigger_point, 'seconds.') time.sleep(trigger_point) sunset_trigger_active = True
def get_sun_event(today): config = configparser.ConfigParser() config.read("Twitter_keys.cfg") lat = config['Astral']['lat'] lon = config['Astral']['lon'] year = today.year month = today.month day = today.day home = astral.LocationInfo('MyHome', 'Bavaria', 'Europe/Berlin', lat, lon) s = sun(home.observer, date=datetime.date(year, month, day), tzinfo=home.timezone) sunrise = s['sunrise'] sunset = s['sunset'] return sunrise, sunset
def __init__( self, tracker, direction, consumer_key, consumer_secret, access_token, access_token_secret, hashtags=[], logging=True, ): self.tracker = tracker self.direction = direction self.hashtags = hashtags self.logging = logging self.schedule = {} self.scheduler = EventScheduler("tweeter") self.lock = threading.RLock() # set up location data tf = TimezoneFinder() self.location = astral.LocationInfo( "AIS Station", "Earth", tf.timezone_at(lat=self.tracker.lat, lng=self.tracker.lon), self.tracker.lat, self.tracker.lon, ) # set up camera self.camera = PiCamera() # set up Twitter connection auth = tweepy.OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_token, access_token_secret) self.twitter = tweepy.API(auth) self.scheduler.start() # register callback self.tracker.message_callbacks.append(self.check)
def init(entry): try: if entry.config['latitude'] is not None: entry.location = astral.location.Location( astral.LocationInfo(name=entry.config['city'], timezone=entry.config['timezone'], latitude=entry.config['latitude'], longitude=entry.config['longitude'])) else: entry.location = astral.location.Location( astral.geocoder.lookup(entry.config['city'], astral.geocoder.database())) except: logging.exception("Location not configured correctly") entry.location = None entry.sun_updated = 0 run(entry)
def load_config(): global location_info, programs_config # Load location configuration try: location_config = json.load(open(location_config_file)) except: logger.exception( 'Failed to load location config file {}'.format(location_config)) else: # Check config file if 'location' not in location_config: logger.error('Missing location entry in config file {}'.format( location_config)) elif 'latitude' not in location_config[ 'location'] or 'longitude' not in location_config['location']: logger.error( 'Missing latitude and/or longitude entry in config file {}'. format(location_config)) else: latitude = float(location_config['location']['latitude']) longitude = float(location_config['location']['longitude']) location_info = astral.LocationInfo('Name', 'Region', "Time zone", latitude, longitude) # Load programs try: programs_config = json.load(open(programs_config_file)) except: logger.exception( 'Failed to load config file {}'.format(programs_config_file)) programs = None else: if 'programs' not in programs_config: logger.error('Missing programs entry in config file {}'.format( programs_config_file)) programs_config = None
# A script to turn on and off relays connected to the Rasbperry Pi GPIO pins at certain times of the day. # These relays can be connected to an outdoor lighting setup # Imports... import astral import datetime import pytz from astral.sun import sun import RPi.GPIO as GPIO import time # Set your location here tz = "America/Los_Angeles" location = astral.LocationInfo( name="Seattle", region="USA", timezone=tz, latitude=47.6304, longitude=-122.3631) # how long to sleep our loop for... sleep_seconds: int = 30 # number of minutes before sunset to turn the lights on. mins_before_sunset: int = 30 # turn off at this local time (11:30 pm) off_at_hour_minute: datetime.time = datetime.time(21, 14) # GPIO pins for Raspberry Pi GPIO.setmode(GPIO.BCM) GPIO.setwarnings(False) pinList = [2, 3, 4, 17, 27, 22, 10, 9]
import time import datetime from functools import wraps import astral from astral import sun from src.controller import vlc, bulb from . import helpers from src.logger import log location = astral.LocationInfo(timezone='Europe/Berlin', latitude=49.878708, longitude=8.646927) def run_at(hour: int, minute: int): target = datetime.time(hour, minute) def actual_decorator(function): @wraps(function) def wrapper(*args, **kwargs): now = time.localtime() curr = datetime.time(now.tm_hour, now.tm_min) if curr == target: function(*args, **kwargs) return wrapper return actual_decorator def late(vlamp=vlc.nvl): log.info('launching late profile') vlamp.brightness.change(1, 1800, abort_new=True)
# NOAA Data basic_info = "https://tidesandcurrents.noaa.gov/api/datagetter?date=today&product=predictions&datum=mllw&interval=hilo&format=json&units=metric&time_zone=lst_ldt&station=" adv_info = "https://tidesandcurrents.noaa.gov/api/datagetter?date=today&product=predictions&datum=mllw&format=json&units=metric&time_zone=lst_ldt&station=" stationID = "8418557" # Get the data from NOAA times = json.loads(requests.get(basic_info + stationID).text)['predictions'] # Calculate the time of dawn and dusk # Note: only the timezone and lat+lon actually matter. The names are just for fun ocean_park = astral.LocationInfo(name='Ocean Park', region='Maine', timezone='US/Eastern', latitude=43.5, longitude=-70.383) sun_times = sun(ocean_park.observer, date=today, tzinfo=ocean_park.timezone) timezone = pytz.timezone("US/Eastern") # Schedule the execution of the other scripts notify_times = [] for time in times: if (time['type'] == 'H'): continue # I love Python day, time = time['t'].split()
from datetime import datetime import astral import json import os import pytz import sys import time if len(sys.argv) < 2: print('Please give a config file :(', file=sys.stderr) sys.exit(1) with open(sys.argv[1]) as fp: config = json.load(fp) loc = astral.LocationInfo() loc.name = config['city'] loc.region = config['region'] loc.timezone = config['timezone'] loc.latitude = config['latitude'] loc.longitude = config['longitude'] loc.elevation = config['elevation'] tz = pytz.timezone(loc.timezone) night = config['night'] day = config['day'] def ease_up(amt, low, high): '''Cubic easing out'''
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) df = sunriset.to_pandas(start_date, latitude, longitude, -7, number_of_years) for index, row in df.iterrows(): up = row['Sunrise'] down = row['Sunset'] print(index, up) print(index, down) 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)) # In[ ]: df # In[ ]: x = time.monotonic_ns() y = time.monotonic_ns() y - x z = time.monotonic_ns() - time.monotonic_ns() print(y - x, abs(z))
canv = Image.new("1", (128, 64), 0) dr = ImageDraw.Draw(canv) font1 = ImageFont.truetype("Ubuntu-B.ttf", 50) font2 = ImageFont.truetype("Ubuntu-Th.ttf", 13) font3 = ImageFont.truetype("Ubuntu-B.ttf", 19) font4 = ImageFont.truetype("Ubuntu-B.ttf", 24) font5 = ImageFont.truetype("Ubuntu-B.ttf", 28) font6 = ImageFont.truetype("Ubuntu-Th.ttf", 12) ## sunrise sunset constants and global variables mycity = astral.LocationInfo(name='Berlin', region='Germany', timezone='Europe/Berlin', latitude=52.4217, longitude=13.5702) observer = mycity.observer observer.elevation = 90.0 Berlin_tz = pytz.timezone(mycity.timezone) lastday = 0 sunrise_m = 0 sunset_m = int(24 * 60) ## pages def page1(): #font = ImageFont.truetype("ubuntu/Ubuntu-B.ttf", 50) now = time.localtime() hh = now.tm_hour
def set_locale(self, name, region, tzname, lat, lon): """Set locale.""" self.location = astral.location.Location( astral.LocationInfo((name, region, tzname, lat, lon)))
def sunrise_sunset(iso8601_time_string, longitude, latitude): """ title:: sunrise_sunset description:: This method will determine the sunrise/sunset times for the date in the provided time string at the longitude and latitude speciied. attributes:: iso8601_time_string An ISO8601-formatted time string containing the date for which the sunrise and sunset times will be determined. The time string has the form 2020-11-15T00:19:49.511Z in UTC. longitude The longitude (decimal format) for the location at which to determine the sunrise and sunset times. Longitude is specified in the range [-180, 180] (Eastern longitudes are positive). latitude The latitude (decimal format) for the location at which to determine the sunrise and sunset times. Latitude is specified in the range [-90, 90] (Northern latitudes are positive). returns:: A two-element tuple containing the ISO8601 time strings representing the sunrise and sunset times, respectively [UTC]. author:: Carl Salvaggio copyright:: Copyright (C) 2020, Rochester Institute of Technology license:: GPL version:: 1.0.0 disclaimer:: This source code is provided "as is" and without warranties as to performance or merchantability. The author and/or distributors of this source code may have made statements about this source code. Any such statements do not constitute warranties and shall not be relied on by the user in deciding whether to use this source code. This source code is provided without any express or implied warranties whatsoever. Because of the diversity of conditions and hardware under which this source code may be used, no warranty of fitness for a particular purpose is offered. The user is advised to test the source code thoroughly before relying on it. The user must assume the entire risk of using the source code. """ # Parse the required values from the ISO8601 time string Y = int(iso8601_time_string[0:4]) M = int(iso8601_time_string[5:7]) D = int(iso8601_time_string[8:10]) # Specify the Astral location information object location = \ astral.LocationInfo(None, None, None, latitude, longitude) # Compute the solar positional parameters for the specified date/location solar_parameters = \ astral.sun.sun(location.observer, date=datetime.date(Y, M, D)) sunrise = str(solar_parameters["sunrise"])[0:23] sunset = str(solar_parameters["sunset"])[0:23] sunrise = sunrise[:10] + 'T' + sunrise[11:] + 'Z' sunset = sunset[:10] + 'T' + sunset[11:] + 'Z' return sunrise, sunset