def zon(opofonder): city = LocationInfo() city.region = "Netherlands" ###voor nijverdal city.name = "Nijverdal" city.latitude = 52.366146 city.longitude = 6.443098 ###Voor Meppel city.name = "Meppel" city.latitude = 52.701499 city.longitude = 6.232482 tijdzoneAmsterdam = timezone("Europe/Amsterdam") nu = datetime.datetime.now() city.timezone = tijdzoneAmsterdam s = sun(city.observer, date=nu, tzinfo=tijdzoneAmsterdam) if opofonder == "onder": return (f'ondergang: {s["sunset"]}') if opofonder == "op": return (f'opkomst : {s["sunrise"]}')
def calculate_sunrise_of_tomorrow_and_bedtime(): global sunriseTomorrow, bedtimeTonight, wakeTimeTomorrow, wakeClockTimeTomorrow global showBedtimeTime, showBedtimeCountdownTime tomorrow = get_localized_time() + timedelta(days=1) if get_localized_time() < get_localized_time().replace( hour=c.DAILY_RECALCULATION_TIME.hour, minute=c.DAILY_RECALCULATION_TIME.minute): tomorrow = get_localized_time() s = sun(c.CITY.observer, date=tomorrow.date(), tzinfo=c.CITY.timezone) sunriseTomorrow = s["sunrise"] sunriseTomorrow = sunriseTomorrow.replace(second=0) # keep things fair bedtimeTonight = sunriseTomorrow - timedelta( seconds=c.CALCULATED_BEDTIME_BEFORE_SUNRISE) wakeTimeTomorrow = sunriseTomorrow - timedelta( seconds=c.CALCULATED_WAKE_TIME_BEFORE_SUNRISE) wakeClockTimeTomorrow = wakeTimeTomorrow - timedelta( seconds=c.MORNING_CLOCK_TIME_LENGTH) showBedtimeCountdownTime = bedtimeTonight - timedelta( seconds=c.BEDTIME_COUNTDOWN_LENGTH) showBedtimeTime = bedtimeTonight - timedelta( seconds=c.DISPLAY_BEDTIME_LENGTH) print(bedtimeTonight) print(wakeTimeTomorrow)
def get_local_time_of(): location = data["location"] geo_data = get_geodata(location) city = LocationInfo() city.latitude = geo_data["latitude"] city.longitude = geo_data["longitude"] city.timezone = geo_data["timezone"] timezone = city.timezone local_tz = pytz.timezone(timezone) datetime_day_start = datetime.datetime.now()\ .replace(hour=0, minute=0, second=0, microsecond=0) current_sun = sun(city.observer, date=datetime_day_start) local_time_of = lambda x: current_sun[x]\ .replace(tzinfo=pytz.utc)\ .astimezone(local_tz)\ .strftime("%H:%M:%S") return local_time_of
def _doDownload(self): latitude = self.config['SolCast'].getfloat('Latitude') longitude = self.config['SolCast'].getfloat('Longitude') location = LocationInfo('na', 'na', 'UTC', latitude=latitude, longitude=longitude) now_utc = datetime.now(timezone.utc) mySun = sun(location.observer, date=now_utc) retVal = False if self._force or (now_utc > mySun['sunrise'] and now_utc < mySun['sunset'] ): # storeDB enabled, SolCast enabled, daylight if self._storeDB or self._storeInflux: if self._storeDB: self._db = DBRepository(self.config) self.last_issue = self._db.getLastIssueTime(self.SQLTable) if self._storeInflux: self._influx = InfluxRepo( self.config ) # need to open Influx to later load data else: self._influx = InfluxRepo(self.config) self.last_issue = self._influx.getLastIssueTime( self.SQLTable) delta_t = round( (now_utc - self.last_issue).total_seconds() / 60) if self._force or delta_t > self._interval: # download SolCast again retVal = True print("Message - downloading SolCast data at (UTC): " + str(now_utc)) else: print( "Warning --- getting SolCast data not supported without database storage enabled (storeDB or storeInflux)" ) return (retVal)
def zon(opofonder): city = LocationInfo() city.region = "Netherlands" ###voor nijverdal city.name = "Nijverdal" city.latitude = 52.366146 city.longitude = 6.443098 ###Voor Meppel city.name = "Meppel" city.latitude = 52.701499 city.longitude = 6.232482 tijdzoneAmsterdam = timezone("Europe/Amsterdam") nu = datetime.datetime.now() city.timezone = tijdzoneAmsterdam # print ("Huidige tijd : ") # print (nu.strftime("%Y-%m-%d %H:%M:%S")) s = sun(city.observer, date=nu ,tzinfo=tijdzoneAmsterdam ) # print(city.name) # print(city.latitude) # print(city.longitude) # print('Zon') if opofonder == "onder": # print((f'ondergang: {s["sunset"]}\n')) return((f'ondergang: {s["sunset"]}\n')) # return s["sunrise"] # return "1846" if opofonder == "op": print((f'opkomst : {s["sunrise"]}\n')) return s["sunset"]
def isDay(): """Checks if the time is after sunset Returns: bool: Day time """ import datetime from pytz import timezone, utc from astral import LocationInfo from astral.sun import sun import geocoder g = geocoder.ip('me') city = LocationInfo() city.latitude = g.latlng[0] city.longitude = g.latlng[1] s = sun(city.observer, date=datetime.date.today()) # This presumably depends on the computer's timezone being correct now = utc.localize(datetime.datetime.utcnow()) return s['dawn'] < now < s['dusk']
def solar_day(self, t, mode='dict'): """ This method returns day information for the given timestamp at the given location :param t: Timestamp when the information must be computed :type t: str, datetime.datetime, pandas.Timestamp :param mode: Return type (must be in {'astral', 'dict', 'serie'}), defaults to dict :type mode: str :return: Day information for the given timestamp :rtype: astral.sun.sun, dict, pandas.Series """ from astral import sun modes = {'astral', 'dict', 'serie'} if mode not in modes: raise BadParameter("Mode must be in {}, received '{}' instead".format(modes, mode)) s = sun.sun(self.city.observer, date=t) if mode == 'astral': return s elif mode == 'dict': return dict(s) else: return pd.Series(dict(s), index=[t])
def calculate_sunrise_sunset(place): start_date = datetime.date.today() - datetime.timedelta(days=180) end_date = datetime.date.today() + datetime.timedelta(days=365) location_info = LocationInfo( place["address"], "", place["time_zone"], place["latitude"], place["longitude"] ) day = start_date day_infos = [] tz = pytz.timezone(place["time_zone"]) while day <= end_date: info = sun.sun(location_info.observer, date=day) day_info = { "place": place["slug"], "day": day.isoformat(), } day_info.update( { key: value.astimezone(tz).time().isoformat(timespec="seconds") for key, value in info.items() } ) day_infos.append(day_info) day += datetime.timedelta(days=1) return day_infos
def update(self, dt=None, offset=datetime.timedelta(0)): self.now = datetime.datetime.now(tz=self.timezone) + offset if dt is None else dt + offset self.sun = sun(self.city.observer, date=self.now, tzinfo=self.timezone)
kwargs: Dict[str, Any] = {} kwargs["observer"] = obs if args.date is not None: try: kwargs["date"] = datetime.datetime.strptime(args.date, "%Y-%m-%d").date() except: # noqa: E0722 kwargs["date"] = datetime.date.today() sun_as_str = {} format_str = "%Y-%m-%dT%H:%M:%S" if args.tzname is None: tzinfo = pytz.utc format_str += "Z" else: tzinfo = pytz.timezone(loc.timezone) # type: ignore format_str += "%z" kwargs["tzinfo"] = tzinfo s = sun.sun(**kwargs) for key, value in s.items(): sun_as_str[key] = s[key].strftime(format_str) sun_as_str["timezone"] = tzinfo.zone sun_as_str["location"] = f"{loc.name}, {loc.region}" print(json.dumps(sun_as_str))
#! /usr/bin/python3 from astral import LocationInfo import datetime from astral.sun import sun # location from termux-location city = LocationInfo("Belize City", "BZ", "America/Belize", 17.5149, -88.2229) print((f"Information for {city.name}/{city.region}\n" f"Timezone: {city.timezone}\n" f"Latitude: {city.latitude:.02f}; Longitude: {city.longitude:.02f}\n")) #date=datetime.date(2020, 11, 9) date = datetime.datetime.today() s = sun(city.observer, date, tzinfo=city.timezone) print(date.strftime("%A %d. %B %Y")) print((f'Dawn: {s["dawn"].strftime("%H:%M:%S %z")}\n' f'Sunrise: {s["sunrise"].strftime("%H:%M:%S")}\n' f'Noon: {s["noon"]}\n' f'Sunset: {s["sunset"]}\n' f'Dusk: {s["dusk"]}\n')) print(type(s['dawn'])) #29.2829243, -96.8658090
level=logging.ERROR, format='%(asctime)s %(levelname)s - %(message)s', datefmt='%Y-%m-%d %H:%M:%S', ) # # Kill processes on ports 8080 and 8090, needed for Google Authentication #os.system("fuser -k 8080/tcp") #os.system("fuser -k 8090/tcp") # 1) Check time and see if sun still up from astral import LocationInfo from astral.sun import sun import datetime import pytz city = LocationInfo("Antwerp", "Belgium", "Europe/Brussels", 51.26, 4.4) s = sun(city.observer, date=datetime.date.today()) local = pytz.timezone("Europe/Brussels") current_time = local.localize(datetime.datetime.now()) dawn = s["dawn"].astimezone(local) sunrise = s["sunrise"].astimezone(local) sunset = s["sunset"].astimezone(local) dusk = s["dusk"].astimezone(local) if current_time < sunrise or current_time > sunset: logging.critical('No sunlight, no picture') exit(0) # 2) Take picture import gphoto2 as gp from time import sleep
def gmAll(): # initialize data = request.get_json() data['text'] = data['text'].strip() message = data['text'].split() count = 0 send = None # find bot id conn = sqlite3.connect('pancake.db') c = conn.cursor() for row in c.execute(f"SELECT * FROM chats WHERE id = ?", (data['group_id'], )): botid = row[2] accesstoken = row[0] try: botid except: print("invalid group") return ("invalid group") headers = { 'content-type': 'application/json', 'x-access-token': accesstoken } getInfo = requests.get('https://api.groupme.com/v3/users/me', headers=headers) getInfo = getInfo.json()['response'] user_id1 = getInfo['user_id'] c.close() if data['sender_type'] == 'system': if "added the Pancake bot" in data['text']: time.sleep(0.5) send = "Hi! I'm Pancake. I'm a fun GroupMe bot designed to spice up any groupchat!\n\nHere are a list of commands:\n\np!lmgtfy {search term}\np!pick {option 1},{option 2}\np!coinflip\np!urban {search term}\np!love {firstname1} {firstname2}\np!madgab (use command twice)\np!8ball {your question}\np!sun\np!joke\n\np!help\np!leave (can only be used by owner)\np!ban/p!unban @whoever (can only be used by owner)\n\nI highly recommend using p!madgab to start some friendly competition in this groupchat!" if data['sender_type'] == 'user': conn = sqlite3.connect('databases/banned.db') c = conn.cursor() adminList = [] for row in c.execute(f"SELECT * FROM banned"): adminList.append(row[0]) if int(data['user_id']) in adminList: return ("banned user") c.close() conn = sqlite3.connect('databases/whitelist.db') c = conn.cursor() adminList = [] for row in c.execute(f"SELECT * FROM white WHERE group_id = ?", (data['group_id'], )): adminList.append(row[0]) if data['user_id'] == user_id1: pass elif adminList == []: pass elif data['user_id'] not in adminList: return ("banned user") c.close() if ((str(message[0])) == 'p!ban') and (str(data['sender_id']) == user_id1): conn = sqlite3.connect('databases/banned.db') c = conn.cursor() try: for x in data['attachments'][0]['user_ids']: c.execute("INSERT INTO banned (user_id) VALUES (?)", (x, )) conn.commit() send = f"banned member" except Exception as e: print(str(e)) send = "error" c.close() elif ((str(message[0])) == 'p!unban') and (str(data['sender_id']) == user_id1): conn = sqlite3.connect('databases/banned.db') c = conn.cursor() try: send = None for x in data['attachments'][0]['user_ids']: c.execute("DELETE FROM banned WHERE user_id = ?", (x, )) conn.commit() send = "unbanned member" if send == None: send = "member was not banned" except: send = "error" c.close() elif ((str(message[0])) == 'p!whitelist') and (str(data['sender_id']) == user_id1): if message[1].lower() == "add": conn = sqlite3.connect('databases/whitelist.db') c = conn.cursor() try: for x in data['attachments'][0]['user_ids']: c.execute( "INSERT INTO white (user_id, group_id) VALUES (?,?)", (x, data['group_id'])) conn.commit() send = f"added member to whitelist" except Exception as e: print(str(e)) send = "error" c.close() if message[1].lower() == "remove": conn = sqlite3.connect('databases/whitelist.db') c = conn.cursor() try: send = None for x in data['attachments'][0]['user_ids']: c.execute( "DELETE FROM white WHERE user_id = ? and group_id = ?", (x, data['group_id'])) conn.commit() send = "removed member" if send == None: send = "member was not removed" except Exception as e: print(str(e)) send = "error" c.close() if message[1].lower() == "off": conn = sqlite3.connect('databases/whitelist.db') c = conn.cursor() try: c.execute("DELETE FROM white WHERE group_id = ?", (data['group_id'], )) conn.commit() send = "whitelist off" except: send = "error" c.close() #leave if message[0].lower() == 'p!leave' and data['user_id'] == user_id1: conn = sqlite3.connect('pancake.db') c = conn.cursor() c.execute("DELETE FROM chats WHERE id = ?", (data['group_id'], )) conn.commit() c.close() params = {"bot_id": botid, "text": "pancake is shutting down"} create = requests.post('https://api.groupme.com/v3/bots/post', headers=headers, params=params) params = {"bot_id": botid} create = requests.post('https://api.groupme.com/v3/bots/destroy', headers=headers, params=params) return ("removed") if message[0].lower() == 'p!help': send = "Hi! I'm Pancake. I'm a fun GroupMe bot designed to spice up any groupchat!\n\nHere are a list of commands:\n\np!lmgtfy {search term}\np!pick {option 1},{option 2}\np!coinflip\np!urban {search term}\np!love {firstname1} {firstname2}\np!madgab (use command twice)\np!8ball {your question}\np!sun\np!joke\n\np!help\np!leave (can only be used by owner)\np!ban/p!unban @whoever (can only be used by owner)\n\nI highly recommend using p!madgab to start some friendly competition in this groupchat!" #lmgtfy if message[0].lower() == 'p!lmgtfy': message.pop(0) send = "https://lmgtfy.com/?q=" + '+'.join(message) #choose elif message[0].lower() == 'p!pick': text = data['text'][6:].split(",") for i in range(len(text)): text[i] = text[i].strip() num = random.randint(0, len(text) - 1) send = "i pick \"" + text[num] + "\"" #coinflip elif message[0].lower() == 'p!coinflip': num = random.randint(0, 11) listOne = [0, 1, 2, 3, 4, 5] listTwo = [6, 7, 8, 9, 10, 11] if num in listOne: send = "Heads" elif num in listTwo: send = "Tails" #urban elif message[0].lower() == 'p!urban': message.pop(0) urbanTerm = ' '.join(message) urban = requests.get( f"http://api.urbandictionary.com/v0/define?term={urbanTerm}") try: send = urban.json()['list'][0]['definition'] except IndexError: send = f"couldn't find a definition for {urbanTerm}" #love elif message[0].lower() == 'p!love': try: first = message[1].lower() second = message[2].lower() love = requests.get( f"https://www.lovecalculator.com/love.php?name1={first}&name2={second}" ) lovesoup = BeautifulSoup(love.text, "lxml") score = lovesoup.findAll( "div", {"class": "result__score"})[0].text.strip() send = score except: send = "invalid syntax" #madgab elif message[0].lower() == 'p!madgab': conn = sqlite3.connect('databases/madgab.db') c = conn.cursor() questions = [] answers = [] channels = [] requestions = [] for x in open("databases/question.txt", "r"): questions.append(x) for x in open("databases/answer.txt", "r"): answers.append(x) for row in c.execute(f"SELECT * FROM gameplay"): channels.append(row[0]) requestions.append(row[1]) if data['group_id'] in channels: active = True else: active = False if active == True: sendAnswer = 0 for x in range(len(channels)): if data['group_id'] == channels[x]: sendAnswer = answers[int(requestions[x])] c.execute("DELETE FROM gameplay WHERE channel = ?", (data['group_id'], )) conn.commit() send = sendAnswer else: num = random.randint(0, len(questions) - 1) c.execute( "INSERT INTO gameplay (channel,question) VALUES (?,?)", (data['group_id'], num)) conn.commit() send = questions[num] c.close() elif message[0].lower() == 'p!8ball': responses = [ 'Don’t count on it.', 'It is certain.', 'It is decidedly so.', 'Most likely.', 'My reply is no.', 'My sources say no.', 'Signs point to yes.', 'Very doubtful.', 'Without a doubt.', 'Yes.', 'Yes – definitely.', 'You may rely on it.', 'As I see it, yes.', 'Ask again later.', 'Better to not tell you now.', 'Cannot predict now.', 'Concentrate and ask again.' ] send = random.choice(responses) elif message[0].lower() == "p!sun": city_name = 'Atlanta' city = LocationInfo() city.latitude = 33.7490 city.longitude = -84.3880 city.timezone = 'US/Eastern' s = sun(city.observer, date=datetime.now(), tzinfo=city.timezone) send = f"Sun Info For Atlanta\n\nDawn: {s['dawn'].strftime('%I:%M %p')}\nSunrise: {s['sunrise'].strftime('%I:%M %p')}\nNoon: {s['noon'].strftime('%I:%M %p')}\nSunset: {s['sunset'].strftime('%I:%M %p')}\nDusk: {s['dusk'].strftime('%I:%M %p')}\n" elif message[0].lower() == "p!joke": jheaders = {'User-Agent': 'curl/7.55.1'} joke = requests.get("https://icanhazdadjoke.com/", headers=jheaders) send = joke if send != None: params = {"bot_id": botid, "text": send} create = requests.post('https://api.groupme.com/v3/bots/post', headers=headers, params=params) return ("message received") if send != None: params = {"bot_id": botid, "text": send} create = requests.post('https://api.groupme.com/v3/bots/post', headers=headers, params=params) return ("message received!")
subscribe_future, packet_id = mqtt_connection.subscribe( topic='garden/waterStatus', qos=mqtt.QoS.AT_LEAST_ONCE, callback=on_waterStatus_received) subscribe_result = subscribe_future.result() print('Subscribed with {}'.format(str(subscribe_result['qos']))) refresh_interval = 10 time_fetch_interval = 12 * 60 # Approx. minutes to refetch sunrise/sunset while True: # Initialize Astral time city = LocationInfo(args.city, args.region, args.timezone, args.lat, args.long) s = sun(observer=city.observer, tzinfo=args.timezone) sunrise = s['sunrise'] sunset = s['sunset'] tz = sunrise.tzinfo for i in range(time_fetch_interval): temperature = soil.get_temp() capacitance = soil.moisture_read() print('Temp: ' + str(temperature) + ' Capacitance: ' + str(capacitance)) print('Publishing to topic garden/sensorData...') mqtt_connection.publish(topic='garden/sensorData', payload=json.dumps({ 'temperature': temperature, 'capacitance':
# The order of the pixel colors - RGB or GRB. Some NeoPixels have red and green reversed! # For RGBW NeoPixels, simply change the ORDER to RGBW or GRBW. ORDER = neopixel.GRB #Create pixels object pixels = neopixel.NeoPixel(pixel_pin, num_pixels, brightness=0.03, auto_write=False, pixel_order=ORDER) #Create sun object for Oxford today longitude = -1.2577 lattitude = 51.7520 s = sun(Observer(lattitude, longitude), date=datetime.today(), dawn_dusk_depression=6.0) #Print sun times for info 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')) #Obtain sun times as UNIX timestamps dawn = s["dawn"].timestamp() sunrise = s["sunrise"].timestamp() sunset = s["sunset"].timestamp() dusk = s["dusk"].timestamp()
(2022,1,18,"Feast of Sulṭán (Sovereignty)"), (2022,2,6,"Feast of Mulk (Dominion)"), (2022,2,25,"First Day of Ayyám-i-Há"), (2022,3,2,"Feast of ʻAlá' (Loftiness) - the Fast begins"), (2022,3,21,"Feast of Bahá (Naw-Rúz)"), ] for set_ in sets: year = set_[0] month = set_[1] day = set_[2] event = set_[3] same_day = datetime.date(year,month,day) s_same_day = sun(fukuoka.observer, date=same_day, tzinfo=fukuoka.timezone) same_day_week_day = same_day.strftime('%A') day_before = same_day - datetime.timedelta(1) s_day_before = sun(fukuoka.observer, date=day_before, tzinfo=fukuoka.timezone) day_before_week_day = day_before.strftime('%A') sunset_day_before_pd = pd.Timestamp(s_day_before['sunset']) sunset_day_before_pd = sunset_day_before_pd.ceil('15min').to_pydatetime() hour = sunset_day_before_pd.hour minute = sunset_day_before_pd.minute sunset_same_day_pd = pd.Timestamp(s_same_day['sunset']) sunset_same_day_pd = sunset_same_day_pd.floor('15min').to_pydatetime()
import json import base64 import hmac import hashlib import datetime from astral import LocationInfo from astral.sun import sun # t0 = datetime.datetime.combine(datetime.date.today(), datetime.time(0, 0)) # for x in range(0, 48): # print (t0+datetime.timedelta(minutes=(x*30))) import pytz utc = pytz.UTC city = LocationInfo("Paris", "France", "Europe/Paris", 48.0982983, -1.6051953) s = sun(city.observer, date=datetime.date.today(), tzinfo=city.timezone) 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')) sunrise = (s["sunrise"] + datetime.timedelta(minutes=30)).time() sunset = (s["sunset"] - datetime.timedelta(minutes=30)).time() # tz = pytz.timezone(city.timezone) # time_now = datetime.datetime.now(tz) # if time_now > sunrise and time_now < sunset: # am I in between sunset and dusk? # print("Daylight") # else:
LLA = [-121.64125, 38.10275, -10] longitude = LLA[0] # degrees - longitude of tower location latitude = LLA[1] # degrees - latitude of tower location altitude = LLA[2] # m - altitude of tower location from astral import LocationInfo city = LocationInfo("Sacramento", "California", "US", LLA[1], LLA[0]) from astral.sun import sun daynight = [] for time in plottime: s = sun(city.observer, date=datetime(time.year, time.month, time.day)) sr = s["sunrise"] ss = s["sunset"] if time > sr and time < ss: daynight.append(1) else: daynight.append(0) daynight = np.array(daynight, dtype=bool) # #========================================================================= #%% Ready to loop through channels, then through days (in this case daysun3) day_start = doy[0] day_end = doy[-1]
from datetime import datetime from astral import LocationInfo from astral.sun import sun from dateutil import tz city = LocationInfo("Madrid", "Spain", "Europe/Madrid", 44.419177, -3.703295) print(f"Information for {city.name}/{city.region}") print(f"Timezone: {city.timezone}") print(f"Latitude: {city.latitude:.02f}; Longitude: {city.longitude:.02f}\n") s = sun(city.observer, date=datetime.now()) from_zone = tz.gettz('UTC') madrid_zone = tz.gettz('Europe/Madrid') japan_zone = tz.gettz('Asia/Tokyo') china_zone = tz.gettz('Asia/Shanghai') moscow_zone = tz.gettz('Europe/Moscow') lisbon_zone = tz.gettz('Europe/Lisbon') ny_zone = tz.gettz('America/New_York') def generateSecondaryText(phase, city): return "{city} time at Madrid's {phase}".format(city=city, phase=phase) def printOutput(time, from_zone, to_zone, text): print( f'{text} {time.replace(tzinfo=from_zone).astimezone(to_zone).strftime("%d/%m/%Y %H:%M:%S")}' )
debug_print('Time to take a picture') take_picture(filename) time.sleep(args.interval) ##### Setting up the start and stop times for the day ##### ##### These either come from the command paramters or from dusk and dawn. ##### if args.startstop: start_hour = int(args.startstop[0].split(':')[0]) start_min = int(args.startstop[0].split(':')[1]) stop_hour = int(args.startstop[1].split(':')[0]) stop_min = int(args.startstop[1].split(':')[1]) else: s = sun(loc.observer, date=datetime.date.today(), tzinfo=loc.timezone) start_hour = int(str(s['dawn'])[11:13]) - prepost start_min = int(str(s['dawn'])[14:16]) stop_hour = int(str(s['dusk'])[11:13]) + prepost stop_min = int(str(s['dusk'])[14:16]) ##### Now that we have subtracted and added to time, we need to make sure that the ###### ##### numbers for minute and hour are still within what we expect for time. If we ###### ##### mess this up then we will end up in a loop forever later in the program. ###### if start_min > 59: start_min = start_min - 60 start_hour = start_hour + 1 if stop_min > 59: stop_min = stop_min - 60
def run_loop(config): delta = 0 base = config["base_path"] debugLog = config["debugLog"] # assumption that this program won't run for weeks so calc dawn/dusk once # check location is in astral db via online documentation city = lookup(config["location"], database()) citysun = sun(city.observer, date=now) Dawn = citysun["dawn"].astimezone(timezone(city.timezone)).time() Dusk = citysun["dusk"].astimezone(timezone(city.timezone)).time() while True: # grab config file try: filepath = config["base_path"] + "/config.yaml" with open(filepath) as f: config = yaml.load(f, Loader=yaml.FullLoader) debugLog = config["debugLog"] except FileNotFoundError: logger.info("--<opening '%s' failed>---", filepath) if debugLog: logger.info(" ") logger.info("=========== start capture ==========") now = datetime.now() startTime = config["start_time"] endTime = config["end_time"] pause = config["time_delay"] if debugLog: logger.info("Pause interval: %s", str(pause)) # set exposure or drop out of loop if night mode nowTime = now.time() if Dawn < nowTime and nowTime < Dusk: # Day if config["shooting_mode"] == "night": if debugLog: logger.info( "Shot cancelled as time is outside time window") continue exposureMode = 'auto' else: # Night exposureMode = 'night' take_shot = check_shot(startTime, endTime) if take_shot is True: path = prepare_dir(base, now) name = '{:%Y%m%d-%H%M%S-}'.format(now) + exposureMode + '.jpg' if debugLog: logger.info("Capturing %s in %s mode", name, exposureMode) fileName = base + "/" + path + "/" + name os_command = make_os_command(config, exposureMode, fileName) os.system(os_command) if debugLog: logger.info("Command: %s", os_command) delta = int((datetime.now() - now).seconds) if debugLog: logger.info("Capture File: %s/%s secs", str(delta), str(pause)) else: if debugLog: logger.info("Shot cancelled as time is outside time window") # night shots take about 10 x shooting time if pause - delta > 0: time.sleep(pause - delta)
plt.legend() fig.savefig(f"test-irradiance-{city}.png") plt.show() if __name__ == "__main__": for city in locations: values = dict(pysolar=[], solarpy=[], pvlib=[]) lat, lon = locations[city] timezone = timezones[city] loc_info = LocationInfo(timezone=timezone, latitude=lat, longitude=lon) # this gives 'dawn', 'sunrise', 'noon', 'sunset' and 'dusk' sun_times = sun(loc_info.observer, date=DAY.date(), tzinfo=loc_info.timezone) local_datetimes = [ dt.replace(tzinfo=pytz.timezone(timezones[city])) for dt in datetimes ] for dt in local_datetimes: irrad_pysolar = irradiance_by_pysolar(lat, lon, dt) values["pysolar"].append(irrad_pysolar) irrad_solarpy = irradiance_by_solarpy(lat, lon, dt, timezone) values["solarpy"].append(irrad_solarpy) irrad_pvlib = irradiance_by_pvlib(lat, lon, dt) values["pvlib"].append(irrad_pvlib) print( f"For {city} at {dt} {timezones[city]} ― pysolar: {irrad_pysolar:.2f}, solarpy: {irrad_solarpy:.2f}, pvlib: {irrad_pvlib:.2f}"
def run(self): global stats temp_upd = None if plugin_options['use_footer']: temp_upd = showInFooter() # instantiate class to enable data in footer temp_upd.button = "sunrise_and_sunset/status" # button redirect on footer temp_upd.label = _('Sunrise and Sunset') # label on footer msg = _('Waiting to state') temp_upd.val = msg.encode('utf8').decode('utf8') # value on footer try: from astral.geocoder import database except ImportError: log.clear(NAME) log.info(NAME, _('Astral is not installed.')) log.info(NAME, _('Please wait installing astral...')) cmd = "pip3 install astral" run_command(cmd) log.info(NAME, _('Astral is now installed.')) while not self._stop_event.is_set(): try: if plugin_options['use_astro']: log.clear(NAME) city = None found_name = '' found_region = '' found_timezone ='' found_latitude = 0 found_longitude = 0 try: if plugin_options['location'] != 0: # 0 is none location from astral.geocoder import database, lookup find_loc = city_table[plugin_options['location']] city = lookup(find_loc, database()) # return example: LocationInfo(name='Addis Ababa', region='Ethiopia', timezone='Africa/Addis_Ababa', latitude=9.033333333333333, longitude=38.7) found_name = city.name found_region = city.region found_timezone = city.timezone found_latitude = city.latitude found_longitude = city.longitude else: if plugin_options['custom_location'] and plugin_options['custom_region'] and plugin_options['custom_timezone'] and plugin_options['custom_lati_longit']: from astral.geocoder import add_locations, database, lookup db = database() _loc = '{},{},{},{}'.format(plugin_options['custom_location'], plugin_options['custom_region'], plugin_options['custom_timezone'], plugin_options['custom_lati_longit']) add_locations(_loc, db) # "Somewhere,Secret Location,UTC,24°28'N,39°36'E" city = lookup(plugin_options['custom_location'], db) found_name = city.name found_region = city.region found_timezone = city.timezone found_latitude = city.latitude found_longitude = city.longitude else: log.info(NAME, _('You must fill in all required fields (location, region, timezone/name, latitude and longitude!')) city = None s = None if city is not None: log.info(NAME, _('Found city')) log.info(NAME, _('Name') + ': {}'.format(found_name)) log.info(NAME, _('Region') + ': {}'.format(found_region)) log.info(NAME, _('Timezone') + ': {}'.format(found_timezone)) log.info(NAME, _('Latitude') + ': {}'.format(round(found_latitude, 2))) log.info(NAME, _('Longitude') + ': {}'.format(round(found_longitude, 2))) import datetime from astral.sun import sun today = datetime.date.today() _day = int(today.strftime("%d")) _month = int(today.strftime("%m")) _year = int(today.strftime("%Y")) s = sun(city.observer, date=datetime.date(_year, _month, _day), tzinfo=found_timezone) log.info(NAME, '_______________ ' + '{}'.format(today) + ' _______________') log.info(NAME, _('Dawn') + ': {}'.format(s["dawn"].strftime("%H:%M:%S"))) log.info(NAME, _('Sunrise') + ': {}'.format(s["sunrise"].strftime("%H:%M:%S"))) log.info(NAME, _('Noon') + ': {}'.format(s["noon"].strftime("%H:%M:%S"))) log.info(NAME, _('Sunset') + ': {}'.format(s["sunset"].strftime("%H:%M:%S"))) log.info(NAME, _('Dusk') + ': {}'.format(s["dusk"].strftime("%H:%M:%S"))) msg = _('Sunrise') + ': {}, '.format(s["sunrise"].strftime("%H:%M:%S")) + _('Sunset') + ': {}'.format(s["sunset"].strftime("%H:%M:%S")) from astral import moon m = moon.phase(datetime.date(_year, _month, _day)) log.info(NAME, _('Moon phase') + ': {}'.format(round(m, 2))) msg += ', ' + _('Moon phase') + ': ' if m < 7: log.info(NAME, '* ' + _('New moon')) msg += _('New moon') elif m >= 7 and m < 14: log.info(NAME, '* ' + _('First quarter')) msg += _('First quarter') elif m >= 14 and m < 21: log.info(NAME, '* ' + _('Full moon')) msg += _('Full moon') elif m >= 21 and m < 28: log.info(NAME, '* ' + _('Last quarter')) msg += _('Last quarter') else: log.info(NAME, '* ' + _('Unkown phase')) msg += _('Unkown phase') except Exception: self.started.set() log.error(NAME, _('Astro plug-in') + ':\n' + traceback.format_exc()) self._sleep(2) else: msg =_(u'Plugin is not enabled') if plugin_options['use_footer']: if temp_upd is not None: temp_upd.val = msg.encode('utf8').decode('utf8') # value on footer else: log.error(NAME, _('Error: restart this plugin! Show in homepage footer have enabled.')) self._sleep(3600) except Exception: self.started.set() log.error(NAME, _('Astro plug-in') + ':\n' + traceback.format_exc()) self._sleep(60)
def getSun(city_name): city = lookup(city_name, database()) return sun(city.observer, date=datetime.date.today())
def __init__(self): self.loc = LocationInfo(name='Hamburg', region='Hamburg, Germany', timezone='Europe/Berlin', latitude=51.0, longitude=10.0) self.tzinfo = self.loc.tzinfo self.sun = sun(self.loc.observer, date=datetime.now(self.loc.tzinfo), tzinfo=self.loc.timezone)
async def tide_data_for_place(place_slug, day=None): db = datasette.get_database("data") place = (await db.execute( "select * from places where slug = :place_slug", {"place_slug": place_slug}, )).first() # Use the timezone to figure out today if day is None: day = datetime.datetime.now(pytz.timezone( place["time_zone"])).date() station_id = place["station_id"] results = await db.execute( TIDE_TIMES_SQL, { "station_id": station_id, "day": day.isoformat(), }, ) tide_times = list(dict(r) for r in results) heights = [{ "time": tide_time["datetime"].split()[-1], "time_pct": round(100 * time_to_float(tide_time["datetime"].split()[-1]), 2), "feet": tide_time["mllw_feet"], } for tide_time in tide_times] if len(heights) < 3: return None minimas, maximas = get_minimas_maximas(heights) location_info = LocationInfo( place["address"], "", place["time_zone"], place["latitude"], place["longitude"], ) tz = pytz.timezone(place["time_zone"]) astral_info = sun.sun(location_info.observer, date=day) # Calculate SVG points, refs https://github.com/natbat/rockybeaches/issues/31 min_feet = min(h["feet"] for h in heights[1:-1]) max_feet = max(h["feet"] for h in heights[1:-1]) feet_delta = max_feet - min_feet svg_points = [] for i, height in enumerate(heights[1:-1]): ratio = (height["feet"] - min_feet) / feet_delta line_height_pct = 100 - (ratio * 100) svg_points.append((i, line_height_pct)) # Figure out the lowest minima that's during daylight sunrise = (astral_info["sunrise"].astimezone(tz).time().isoformat( timespec="minutes")) sunset = (astral_info["sunset"].astimezone(tz).time().isoformat( timespec="minutes")) daytime_minimas = [ m for m in minimas if sunrise <= m["time"] <= sunset ] if daytime_minimas: lowest_daylight_minima = sorted(daytime_minimas, key=lambda m: m["feet"])[0] else: lowest_daylight_minima = None info = { "minimas": minimas, "maximas": maximas, "lowest_daylight_minima": lowest_daylight_minima, "heights": heights[1:-1], "lowest_tide": list(sorted(heights[1:-1], key=lambda t: t["feet"]))[0], "svg_points": " ".join("{},{:.2f}".format(i, pct) for i, pct in svg_points), } info.update({ key: value.astimezone(tz).time().isoformat(timespec="seconds") for key, value in astral_info.items() }) info.update({ "{}_pct".format(key): round( 100 * time_to_float( value.astimezone(tz).time().isoformat(timespec="seconds")), 2, ) for key, value in astral_info.items() }) return info
from astral.geocoder import database, lookup from astral.sun import sun # Configuation CITY = "Austin" # Choose from list of cities in README LED_DAY_BRIGHTNESS = 0.2 # Float from 0.0 (min) to 1.0 (max) LED_NIGHT_BRIGHTNESS= 0.08 # Float from 0.0 (min) to 1.0 (max) # Setup now_utc = datetime.datetime.utcnow() # astral times are in zulu now_local = datetime.datetime.now() year = now_local.date().year month = now_local.date().month day = now_local.date().day city = lookup(CITY,database()) s = sun(city.observer, date=datetime.date(year, month, day)) # query with local day to keep sunset and sunrise on local day not zulu day #times in zulu sunrise = (s["sunrise"]).replace(tzinfo=None) sunset = (s["sunset"]).replace(tzinfo=None) dawn = (s["dawn"]).replace(tzinfo=None) dusk = (s["dusk"]).replace(tzinfo=None) up = sunrise down = sunset if ((now_utc < up) | (now_utc > down)): LED_BRIGHTNESS = LED_NIGHT_BRIGHTNESS print("Nightime. Switching at " + str(up)) elif ((now_utc > up) & (now_utc < down)): LED_BRIGHTNESS = LED_DAY_BRIGHTNESS print("Daytime. Switching at " + str(down)) else: LED_BRIGHTNESS = LED_DAY_BRIGHTNESS
import glob import re import subprocess import sys city = LocationInfo("Berlin", "Germany", "52.5", "13.4") if len(sys.argv) == 2: _date = sys.argv[1] else: _now = datetime.today() - timedelta(days=1) _date = "%d%02d%02d" % (_now.year, _now.month, _now.day) date = datetime.strptime(_date, "%Y%m%d") output_file = date.strftime("%Y%m%d -- %A%e %B.mpg") events = sun(city.observer, date) sunrise = events['sunrise'] sunset = events['sunset'] def is_daylight(hour, minute): if hour < sunrise.hour - 1: return False if hour > sunset.hour + 1: return False return True pattern = "../snapshot%s*.jpg" % (_date) print(pattern) files = glob.glob(pattern)
tuleStaatus = f.readline() f.close() return tuleStaatus tuleStaatus = seis() #print(tuleStaatus) GPIO.setmode(GPIO.BCM) GPIO.setup(pin, GPIO.OUT) if (tuleStaatus != "light override off") and (tuleStaatus != "Manual ON") and ( tuleStaatus != "Manual OFF"): tuleStaatus = "light override off" try: while True: s = sun(city.observer, date=datetime.now(), tzinfo=city.timezone) time_now = utc.localize(datetime.now()) sunrise = s["sunrise"] sunset = s["sunset"] sunsetBetter = sunset.strftime("%Y-%m-%d %H:%M") sunriseBetter = sunrise.strftime("%Y-%m-%d %H:%M") ajad = (f'Sunrise: {sunriseBetter}\n' f'Sunset: {sunsetBetter}\n') #try: #checkstatus = check() #except: continue time.sleep(5) if tuleStaatus == "Manual ON": #try: GPIO.output(pin, True) tekst = "Manual ON\n" tuleStaatus = seis()
def get_sunset(): l = LocationInfo(city_name, "region", city_timezone, city_lat, city_long) s = sun((l.observer), tzinfo=city_timezone) sunrise = s["sunset"] today_sunset = sunrise.strftime("%H:%M") return (today_sunset)