def day(self): now = datetime.date.today() self.observer.date = now length = 40 sunrise = ephem.localtime(self.observer.next_rising(self.sun)) sunset = ephem.localtime(self.observer.next_setting(self.sun)) sunrise = (sunrise.hour + (sunrise.minute / 60.0) + (sunrise.second / 3660.0)) sunset = (sunset.hour + (sunset.minute / 60.0) + (sunset.second / 3660.0)) sunlight = sunset - sunrise sunlight_hours = sunlight # Graph sunrise = int(round(self.map_range(0, length, 0, 24, sunrise))) sunset = int(round(self.map_range(0, length, 0, 24, 24- sunset))) sunlight = int(round(self.map_range(0, length, 0, 24, sunlight))) graph = "[" graph += " " * (sunrise - 1) graph += unichr(0x2591) graph += unichr(0x2593) graph += unichr(0x2588) * (sunlight - 2) graph += unichr(0x2593) graph += unichr(0x2591) graph += " " * (sunset - 1) graph += "]" return "%0.2f hours of sunlight today: %s" % (sunlight_hours, graph)
def get_passes(self): passes_dict = [] # use time of 4PM today for all calculations so that it always gets next rise and set times for this evening mytz = pytz.timezone(self.tz) eptz = pytz.timezone('utc') now = datetime.date.today() afternoon = mytz.localize( datetime.datetime(now.year,now.month,now.day)+ datetime.timedelta(hours=16)) eptafternoon = afternoon.astimezone(eptz) # print "eptafternoon", eptafternoon # setup current location here = ephem.Observer() here.lon = str(self.lon) here.lat = str(self.lat) here.elev = self.alt here.date = eptafternoon # print here # do lookup from NASA website: url = params.nasa_url req = urllib2.Request(url) response = urllib2.urlopen(req) data = response.read() # look for TWO LINE MEAN ELEMENT SET in file table = data.split("TWO LINE MEAN ELEMENT SET")[1] line1 = table.splitlines()[3] line2 = table.splitlines()[4] # print "line 1:", line1 # print "line 2:", line2 iss = ephem.readtle('ISS', \ line1, \ line2) # get next 5 passes, there would never be more than 5 passes after 4PM for apass in range(0,5): iss.compute(here) iss_np = here.next_pass(iss) iss_r = ephem.localtime(iss_np[0]) iss_s = ephem.localtime(iss_np[4]) # print "pass n: iss rise, set:", apass, iss_r, iss_s # Store the data in a list passes_dict.append({"begin_time": iss_r, "end_time": iss_s}) here.date = iss_np[4] # Return all the data return passes_dict
def get_sunrise_sunset(date, lon= -122.3783, lat= 47.7128): """Function accepts a date string, and location float coordinates Function returns local, sunrise and sunset time datetime objects""" import ephem # Make an observer o = ephem.Observer() # PyEphem takes and returns only UTC times. 19:00 is Noon PDT, 20:00 is Noon PST # Using a string conversion and operation, which is probably slow # and could use optimization o.date = str(date) + ' 19:00' # Location of Carkeek Park o.lon = str(lon) # Note that lon should be in string format o.lat = str(lat) # Note that lat should be in string format # Elevation of the beach extending from Carkeek Park o.elev = 0 sunrise=o.previous_rising(ephem.Sun()) # Sunrise sunset =o.next_setting(ephem.Sun()) # Sunset # convert sunrise and sunset to localtime (PDT/PST) local_sunrise = ephem.localtime(ephem.date(sunrise)) local_sunset = ephem.localtime(ephem.date(sunset)) return {'sunrise': local_sunrise, 'sunset': local_sunset}
def update_sun_state(now): # pylint: disable=unused-argument """ Method to update the current state of the sun and set time of next setting and rising. """ observer = ephem.Observer() observer.lat = latitude observer.long = longitude next_rising_dt = ephem.localtime(observer.next_rising(sun)) next_setting_dt = ephem.localtime(observer.next_setting(sun)) if next_rising_dt > next_setting_dt: new_state = STATE_ABOVE_HORIZON next_change = next_setting_dt else: new_state = STATE_BELOW_HORIZON next_change = next_rising_dt logger.info( "Sun:{}. Next change: {}".format(new_state, next_change.strftime("%H:%M"))) state_attributes = { STATE_ATTR_NEXT_RISING: ha.datetime_to_str(next_rising_dt), STATE_ATTR_NEXT_SETTING: ha.datetime_to_str(next_setting_dt) } statemachine.set_state(STATE_CATEGORY, new_state, state_attributes) # +10 seconds to be sure that the change has occured ha.track_time_change(bus, update_sun_state, point_in_time=next_change + timedelta(seconds=10))
def update_sun_state(now): # pylint: disable=unused-argument """ Method to update the current state of the sun and set time of next setting and rising. """ observer = ephem.Observer() observer.lat = latitude # pylint: disable=assigning-non-slot observer.long = longitude # pylint: disable=assigning-non-slot next_rising_dt = ephem.localtime(observer.next_rising(sun)) next_setting_dt = ephem.localtime(observer.next_setting(sun)) if next_rising_dt > next_setting_dt: new_state = STATE_ABOVE_HORIZON next_change = next_setting_dt else: new_state = STATE_BELOW_HORIZON next_change = next_rising_dt logger.info("%s. Next change: %s", new_state, next_change.strftime("%H:%M")) state_attributes = { STATE_ATTR_NEXT_RISING: util.datetime_to_str(next_rising_dt), STATE_ATTR_NEXT_SETTING: util.datetime_to_str(next_setting_dt) } hass.states.set(ENTITY_ID, new_state, state_attributes) # +10 seconds to be sure that the change has occured hass.track_point_in_time(update_sun_state, next_change + timedelta(seconds=10))
def calculateSunriseAndSunset(latitude, longitude): #传入的经纬度必须为浮点型 observer = ephem.Observer() lat_degree = int(latitude) lat_min = int((latitude - lat_degree)*60) lat_sec = (latitude - lat_degree - lat_min/60)*60*60 observer.lat = str(lat_degree) + ':' + str(lat_min) + ':' + str(lat_sec) long_degree = int(longitude) long_min = int((longitude - long_degree)*60) long_sec = (longitude - long_degree - long_min/60)*60*60 observer.long = str(long_degree) + ':' + str(long_min) + ':' + str(long_sec) observer.date = datetime.datetime.utcnow() sun = ephem.Sun(observer) sun_rising_utc = observer.next_rising(sun) sun_setting_utc = observer.next_setting(sun) sun_rising_str_raw = str(ephem.localtime(sun_rising_utc).ctime()) sun_setting_str_raw = str(ephem.localtime(sun_setting_utc).ctime()) sun_rising = sun_rising_str_raw.split(' ')[3] sun_setting = sun_setting_str_raw.split(' ')[3] return (sun_rising,sun_setting)
def update_sat(): """This is the function that updates the satellite object's position info""" try: has_shown_pass = False passing_overhead_msg = sat.name + ' is currently passing overhead' while 1: if is_frozen == False: global p_time p_time = datetime.datetime.utcnow() + displacement grnd.set_date(p_time) global sat sat.compute(grnd.observer) try: my_pass_tuple = grnd.next_pass(sat) start_time = ephem.localtime(my_pass_tuple[0]) end_time = ephem.localtime(my_pass_tuple[4]) if start_time > end_time and (not has_shown_pass): # This can only happen if we're in a pass right now try: notify(passing_overhead_msg) except dbus.DBusException: print passing_overhead_msg has_shown_pass = True elif start_time < end_time and has_shown_pass: has_shown_pass = False except ValueError: # satellite is always below the horizon pass time.sleep(REFRESH_TIME) except Exception as e: print type(e) print e kill_program(1)
def time2angle(venue): ''' Cygnus A RA: 19h 59m 28.3566s Cygnus A Dec: +40 deg 44' 02.096" At Carl's using http://www.latlong.net/convert-address-to-lat-long.html 37.980012 deg lat -122.185800 deg long venue format is tuple ''' HERA = ep.Observer() HERA.long = ep.degrees('-122.185800') HERA.lat = ep.degrees('37.980012') HERA.date = venue HERA.epoch = ep.date(venue) sidereal_time = HERA.sidereal_time() #print ('Sidereal time: %s') %str(sidereal_time) astro_obj = ep.FixedBody() astro_obj._ra = ep.hours('19:59:28.3566') astro_obj._dec = ep.degrees('40:44:02.096') astro_obj.compute(HERA) coordinates_given_time = (ep.degrees(astro_obj.az), ep.degrees(astro_obj.alt)) transit_time = ep.localtime(astro_obj.transit_time) transit_alt = ep.degrees(astro_obj.transit_alt) rise_time_on_given_date = ep.localtime(astro_obj.rise_time) rise_az_on_given_date = ep.degrees(astro_obj.rise_az) set_time_on_given_date = ep.localtime(astro_obj.set_time) set_az_on_given_date = ep.degrees(astro_obj.set_az) return coordinates_given_time, transit_time, \ transit_alt, rise_time_on_given_date, rise_az_on_given_date, \ set_time_on_given_date, set_az_on_given_date, sidereal_time
def when_is_sunrise_and_sunset(ground_position_lat, ground_position_lon, date, date_format = "%d/%m/%Y"): '''when_is_sunrise_and_sunset calculates the sunrise and sunset time at any location on earth for the date given. ground_position_lat = -19.2590 # The latitude of the ground position (int) ground_position_lon = 146.8169 # The longitude of the ground position (int) date = '21/06/2016' # date of the day to find passes on in UTC (string) date_format = "%d/%m/%Y" # the format of thh date string (string) Returns: [sunrise-time, sunset-time)] as datetime objects in the local time zone Contact: [email protected] ''' # check the lat and lons to be sensible. futs.check_for_sensible_lat_long([ground_position_lat, ground_position_lon]) # set up my observer. user = ephem.Observer() user.lat = ground_position_lat user.lon = ground_position_lon user.date = datetime.strptime(date, date_format) # set up the celestial body we're interested in body=ephem.Sun() body.compute() # do the calcs local_sun_rise_set = [ephem.localtime(user.previous_rising(body)),ephem.localtime(user.next_setting(body))] # rise then set return local_sun_rise_set
def updateSchedule(self): weekDays = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'] self.homeLocation.lat = str(self.config.Latitude) self.homeLocation.lon = str(self.config.Longitude) self.homeLocation.date = datetime.datetime.now().strftime("%Y/%m/%d 00:00:00") sunrise = ephem.localtime(self.homeLocation.next_rising(ephem.Sun())) sunset = ephem.localtime(self.homeLocation.next_setting(ephem.Sun())) weekday = weekDays[datetime.datetime.today().weekday()] date = datetime.datetime.today().strftime('%Y/%m/%d') self.LogInfo("Today is "+date+", a "+weekday+", Sunrise is at "+str(sunrise.time())+" and Sunset is at "+ str(sunset.time())); self.currentSchedule = {} for id, event in self.schedule.getSchedule().items(): if ((event.active == "active") and (((event.repeatType == 'weekday') and (weekday in event.repeatValue)) or ((event.repeatType == 'once') and (date == event.repeatValue)))): if (event.timeType == "clock"): eventTime = datetime.time(int(event.timeValue.split(":")[0]), int(event.timeValue.split(":")[1]), 0) elif ((event.timeType == "astro") and (event.timeValue.startswith("sunrise"))): eventTime = (sunrise + datetime.timedelta(minutes=int(event.timeValue[7:] or 0))).time() elif ((event.timeType == "astro") and (event.timeValue.startswith("sunset"))): eventTime = (sunset + datetime.timedelta(minutes=int(event.timeValue[6:] or 0))).time() if (eventTime > datetime.datetime.now().time()): eventTimeStr = "%02d:%02d" % (eventTime.hour, eventTime.minute) if not eventTimeStr in self.currentSchedule: self.currentSchedule[eventTimeStr] = [] self.currentSchedule[eventTimeStr].append([event.shutterIds, event.shutterAction]) self.LogDebug(str(self.currentSchedule))
def print_visinfo(body,location): body.compute(location) # Compute the viewing details # Handle the case when the body is above the horizon (so already rose) if body.alt > 0: # Body might have risen yesterday (is circumpolar) try: body_rise = ephem.localtime(location.previous_rising(body)) r_time = fmt_datetime(body_rise) except ephem.CircumpolarError: r_time = "already up " # Body might not set today (is circumpolar) try: body_set = ephem.localtime(location.next_setting(body)) s_time = fmt_datetime(body_set) except ephem.CircumpolarError: s_time = "doesn't set" # Location-based rise/set modifies body attributes, so need to recompute body.compute(location) print "{:.<19.19s}| Yes | {} | {} | {} | {} | {:5.1f} |".format(body.name, fmt_angle(body.alt),fmt_angle(body.az), r_time, s_time, body.mag) else: # If the body isn't visible either it hasn't yet risen today, or it already set today body_rise = ephem.localtime(location.next_rising(body)) body_set = ephem.localtime(location.next_setting(body)) # Location-based rise/set modifies body attributes, so need to recompute body.compute(location) r_time = fmt_datetime(body_rise) s_time = fmt_datetime(body_set) print "{:.<19.19s}| No | --- | --- | {} | {} | --- |".format(body.name,r_time,s_time)
def output_sat(): """Prints output for the satellite""" s_name = sat.name s_long = sat.sublong s_lat = sat.sublat s_az = sat.az s_alt = sat.alt s_elev = sat.elevation try: pass_tuple = grnd.next_pass(sat) time_of_pass = ephem.localtime(pass_tuple[0]).replace(microsecond=0) set_time = ephem.localtime(pass_tuple[4]).replace(microsecond=0) rise_dt, set_dt = grnd.sunrise_sunset(time_of_pass) night_time = (time_of_pass < rise_dt or time_of_pass > set_dt) except ValueError: time_of_pass = None set_time = None night_time = False print s_name print 'long:', COL_GREEN, s_long, COL_NORMAL print 'lat: ', COL_GREEN, s_lat, COL_NORMAL print 'azimuth:', s_az print 'altitude:', s_alt print 'elevation:', s_elev if time_of_pass is not None: suffix = 'local time ' + ('(night)' if night_time else '(day time)') print 'next pass at' + COL_YELLOW, time_of_pass, COL_NORMAL + suffix print 'end time: ' + COL_YELLOW, set_time, COL_NORMAL else: print COL_PURPLE + 'This satellite will never pass' + COL_NORMAL return
def getCivil(self, shift=0): self._checkDate(shift) now = time.time() self.obs.horizon = "-6" beg_civil_twilight = self.obs.previous_rising(ephem.Sun(), use_center=True) # Begin civil twilight beg_civil_twilight_ts = calendar.timegm(beg_civil_twilight.datetime().utctimetuple()) end_civil_twilight = self.obs.next_setting(ephem.Sun(), use_center=True) # End civil twilight end_civil_twilight_ts = calendar.timegm(end_civil_twilight.datetime().utctimetuple()) beg = self.obs.next_rising(ephem.Sun(), use_center=True) beg_ts = calendar.timegm(beg.datetime().utctimetuple()) if beg_ts < end_civil_twilight_ts: beg_civil_twilight_ts = beg_ts beg_civil_twilight = beg daycivil = 0 if now > beg_civil_twilight_ts and now < end_civil_twilight_ts: daycivil = 1 r = { "status": daycivil, "start": (ephem.localtime(beg_civil_twilight), beg_civil_twilight_ts), "stop": (ephem.localtime(end_civil_twilight), end_civil_twilight_ts), } self._checkDate(0) return r
def getMax(self, shift=0): self._checkDate(shift) now = time.time() self.obs.horizon = "-0:34" sunrise = self.obs.previous_rising(ephem.Sun()) # Sunrise sunrise_ts = calendar.timegm(sunrise.datetime().utctimetuple()) sunset = self.obs.next_setting(ephem.Sun(), use_center=True) sunset_ts = calendar.timegm(sunset.datetime().utctimetuple()) beg = self.obs.next_rising(ephem.Sun(), use_center=True) beg_ts = calendar.timegm(beg.datetime().utctimetuple()) if beg_ts < sunset_ts: sunrise = beg sunrise_ts = beg_ts noon = self.obs.next_transit(ephem.Sun(), start=sunrise) # Solar noon daymax_ts = calendar.timegm(noon.datetime().utctimetuple()) daymax = 0 if now > daymax_ts - 1800 and now < daymax_ts + 1800: daymax = 1 r = { "status": daymax, "start": (ephem.localtime(noon) - timedelta(seconds=1800), daymax_ts - 1800), "stop": (ephem.localtime(noon) + timedelta(seconds=1800), daymax_ts + 1800), } self._checkDate(0) return r
def getReal(self, shift=0): self._checkDate(shift) now = time.time() self.obs.horizon = "-0:34" sunrise = self.obs.previous_rising(ephem.Sun()) # Sunrise sunrise_ts = calendar.timegm(sunrise.datetime().utctimetuple()) sunset = self.obs.next_setting(ephem.Sun()) # Sunset sunset_ts = calendar.timegm(sunset.datetime().utctimetuple()) beg = self.obs.next_rising(ephem.Sun(), use_center=True) beg_ts = calendar.timegm(beg.datetime().utctimetuple()) if beg_ts < sunset_ts: sunrise_ts = beg_ts sunrise = beg dayreal = 0 if now > sunrise_ts and now < sunset_ts: dayreal = 1 r = { "status": dayreal, "start": (ephem.localtime(sunrise), sunrise_ts), "stop": (ephem.localtime(sunset), sunset_ts), } self._checkDate(0) return r
def getExpositionTime(self): """ Calculate exposition time """ try: return ephem.localtime(self._observer.next_setting(self._fixedBody)) - ephem.localtime(ephem.now()) except ephem.CircumpolarError: return except Exception: return
def get_sunset_sunrise(self): o = ephem.Observer() o.lat = parser.get('gps', 'lat') o.long = parser.get('gps', 'long') s = ephem.Sun() s.compute() self.next_rising = ephem.localtime(o.next_rising(s)) self.next_setting = ephem.localtime(o.next_setting(s))
def calc_date_ephem(date_time, location): ''' input: date - datetime.datetime location - location key output: return string of sun/moon ephemeris for 'date', e.g. for 2016 02/28: 06:00 PM sunset - 06:28 PM / 06:58 PM / 07:28 PM 10:06 PM moonrise - 66% One of moonrise or moonset is generated, whichever is after 3pm that day. output: Generate strings of - sunset and twilight - 'moonrise' or 'moonset' / time / % illumination One of moonrise or moonset is generated, whichever is after 3pm that day. E.g.: (('6:00 PM', '06:28 PM', '06:58 PM', '07:28 PM'), ('moonrise', '10:06 PM', '66%')) ''' # Get sunset, twiilight times # set time for noon date = TZ_LOCAL.localize(datetime.datetime.combine(date_time, datetime.time(12, 0))) site = sites[location] site.date = date.astimezone(TZ_UTC) sunset = [] fmt = FMT_HMP # calculate time and format string for horizon in (RuleStartTime.sunset , RuleStartTime.civil , RuleStartTime.nautical , RuleStartTime.astronomical ): site.horizon = rule_horizon[horizon.value] t = TZ_LOCAL.localize(ephem.localtime(site.next_setting(SUN))) t = t.strftime(fmt) # fmt = FMT_HM sunset.append(t) # Get moon data # re-set horizon site.horizon = '0' # find moonrise/set following 3pm date = TZ_LOCAL.localize(date.combine(date, datetime.time(15, 0))) site.date = date.astimezone(TZ_UTC) time_moonset = TZ_LOCAL.localize(ephem.localtime(site.next_setting(MOON))) # figure out which of moonrise/moonset occurs from 3pm-3am if date <= time_moonset < date + HOUR*12: mode = 'moonset ' time = time_moonset.strftime(FMT_HMP) else: mode = 'moonrise' time_moonrise = TZ_LOCAL.localize(ephem.localtime(site.next_rising(MOON))) time = time_moonrise.strftime(FMT_HMP) # Compute moon so illumination is accurate for start of event MOON.compute(date_time) illumination = '{:1.0f}'.format(MOON.phase) moon = (mode, time, illumination) return sunset, moon
def display(self, passes): for p in passes: aos = ephem.localtime(p.aos_time) los = ephem.localtime(p.los_time) print("%02d-%02d %02d:%02d:%02d -- %02d-%02d %02d:%02d:%02d (max el. %5.2f): %s" % (aos.month, aos.day, aos.hour, aos.minute, aos.second, los.month, los.day, los.hour, los.minute, los.second, p.max_elevation, p.sat.name))
def as_columns(self): return ( "{:%a %H:%M:%S}".format(self.date.datetime()), "{:%a %I:%M:%S %p}".format(ephem.localtime(self.date)), "{}".format(timeuntil(ephem.localtime(self.date))), "{0.key:^7}".format(self), "{} {}".format(get_symbol(self.body), self.body.name), "{0.azalt}°".format(self), )
def __init__(self, location, date): self.date = date self.today = self.date.replace(hour=0, minute=0) self.tzOffset = self.today - location.tz.utcoffset(self.today) self.obs = ephem.Observer() self.obs.lat = location.lat self.obs.long = location.long self.obs.date = ephem.Date(self.tzOffset) self.sunrise = ephem.localtime(self.obs.next_rising(ephem.Sun())) self.sunset = ephem.localtime(self.obs.next_setting(ephem.Sun()))
def pdt(date_obj, quasar=True): """Converts date_objects to PDT and outputs local-time formatting Truncates to nearest second INTENDED FOR USE ON QUASAR """ if quasar: lt = ephem.localtime(ephem.date(date_obj - 7*ephem.hour)) # Quasar else: lt = ephem.localtime(date_obj) # Other machine lt = lt.replace(microsecond = 0) return lt
def calc_sunrise_sunset(log): ''' Get todays sunrise and sunset times in the local time zone for a given (hard-coded) latitude/longitude and (optional) elevation. ''' obsvr = ephem.Observer() # this is the lat/long and (optional) elevation for *your* location - in this case Plano TX obsvr.lat, obsvr.long, obsvr.date, obsvr.elevation = '33:2:7', '-96:44:8', ephem.now(), 600 sun = ephem.Sun(obsvr) sunrise = ephem.localtime(obsvr.next_rising(sun)) sunset = ephem.localtime(obsvr.next_setting(sun)) log.info('Sunrise: %s, Sunset: %s\n' % (sunrise, sunset)) return sunrise, sunset
def main(): idnode = sys.argv[1] typecom=sys.argv[2] typeoutpar= sys.argv[3] indexpattern= sys.argv[4] indextemplate=indexpattern+typecom+typeoutpar indexcomc=indexpattern+typecom Config_nodes = ConfigParser.ConfigParser() Config_nodes.read("biomino_nodes.ini") Config_social = ConfigParser.ConfigParser() Config_social.read("biomino_social.ini") Config_msg = ConfigParser.ConfigParser() Config_msg.read("biomino_msg.ini") id_nodes=str(Config_nodes.get('AOnode_ID',idnode)) home = ephem.Observer() sun = ephem.Sun() home.lat = str(Config_nodes.get('AO_ID_lat',idnode)) home.long = str(Config_nodes.get('AO_ID_lon',idnode)) home.elevation =float(str(Config_nodes.get('AO_ID_elev',idnode))) sun.compute(home) nextrise = home.next_rising(sun) nextset = home.next_setting(sun) nextrisea= ephem.localtime(nextrise) nextseta= ephem.localtime(nextset) nextriseh=nextrisea.strftime(fmt) nextseth=nextseta.strftime(fmt) hours = format_timedelta(nextset.datetime() - nextrise.datetime()) template = Template(str(Config_msg.get('AOmino_msg_outpar_msg',indextemplate))) hashtagcoms = str(Config_msg.get('AO_comclass_hashtag',indexcomc)) APP_KEY=str(Config_social.get('AOmino_oauth_consumer_key_tw',idnode)) APP_SECRET=str(Config_social.get('AOnode_OA_consumer_secret_tw',idnode)) OAUTH_TOKEN=str(Config_social.get('AOmino_OA_access_token_tw',idnode)) OAUTH_TOKEN_SECRET=str(Config_social.get('AOmino_OA_access_token_secret_tw',idnode)) twitter = Twython(APP_KEY, APP_SECRET,OAUTH_TOKEN,OAUTH_TOKEN_SECRET) client_args = { "headers": {"accept-charset": "utf-8"}} if typeoutpar =='a': message = template.substitute(idnode=id_nodes,sunriseh=nextriseh,sunseth=nextseth,suntime=hours,hashtagcom=hashtagcoms) else: message = template.substitute(idnode=id_nodes,hashtagcom=hashtagcoms) print message try: twitter.update_status(status=message.decode('latin-1').encode('utf-8')) except TwythonError as e: print e
def CalcObserve(self): home = ephem.Observer() home.lat = self._gslat home.lon = self._gslon #home.date='2014/02/25 1:58:25.00' home.elev = int(self._gselev) sat = ephem.readtle(self._satname, self._tle1, self._tle2) sat.compute(home) sataz = math.degrees(sat.az) satalt = math.degrees(sat.alt) satfreq = float(self._frequency) * self.dopplershift(sat.range_velocity) risetime=ephem.localtime(sat.rise_time) settime=ephem.localtime(sat.set_time) return sataz, satalt, satfreq,risetime,settime,math.degrees(sat.transit_alt)
def test_dateStringNoSeconds(self): import ephem edate = ephem.Date('2013/10/18 18:00:45') # Date/time without seconds fmt ="%Y/%m/%d %H:%M" # Return UTC t_str = str(edate.datetime().strftime(fmt)) self.assertEqual(StrFmt.dateStringNoSeconds(edate), t_str) # Return local import tzlocal tz = tzlocal.get_localzone() tz_str = " " + tz.tzname(ephem.localtime(edate)) t_str = str(ephem.localtime(edate).strftime(fmt)) + tz_str self.assertEqual(StrFmt.dateStringNoSeconds(edate, True), t_str)
def __get_lightness(self, date = datetime.date.today()): """""" hki = ephem.city('Helsinki') hki.date = date sun = ephem.Sun() nsr = ephem.localtime(hki.next_rising(sun)) nss = ephem.localtime(hki.next_setting(sun)) dt = nss - nsr seconds = float(dt.seconds) part_of_day = seconds / (24*60*60) lightness = (part_of_day * 100) + np.random.normal(0, 40) lightness = 20 if lightness < 20 else lightness lightness = 100 if lightness > 100 else lightness return lightness
def get_next_fullmoon_dawn(self): """ Return the date and time of the next dawn and dusk of the next fullmoon @return : the next dawn daytime """ self.mycity.date = self._get_next_fullmoon() dawn = ephem.localtime(self.mycity.next_rising(ephem.Moon(), \ use_center = True)) dusk = ephem.localtime(self.mycity.next_setting(ephem.Moon(), \ use_center = True)) if dawn > dusk: dawn = ephem.localtime(self.mycity.previous_rising(ephem.Moon(), \ use_center = True)) return dawn
def IsDayLight(Lat,Lon,Elev): Observer = ephem.Observer() Observer.lon = str(Lon) Observer.lat = str(Lat) Observer.elevation = int(Elev) Observer.horizon = '-6' start_date_time = ephem.localtime(Observer.next_rising(ephem.Sun(), use_center=True)) stop_date_time = ephem.localtime(Observer.next_setting(ephem.Sun(), use_center=True)) if (start_date_time > stop_date_time): start_date_time = ephem.localtime(Observer.previous_rising(ephem.Sun(), use_center=True)) if (start_date_time < dt.datetime.now()) and ( dt.datetime.now() < stop_date_time): return True else: return False
def calculateSun(data): zcdb = ZipCodeDatabase() local_zip = data['zip'] zipcode = 0 try: zipcode = zcdb[local_zip] except IndexError: print "not a valid zip, using a default: 10001" zipcode = zcdb[10001] # New York now = datetime.datetime.now() o = ephem.Observer() o.pressure = 0 o.horizon = '-0:34' o.date = now o.lat=str(zipcode.latitude) o.long=str(zipcode.longitude) s=ephem.Sun() data['loc'] = zipcode.city+", "+zipcode.state sunrise = str(ephem.localtime(o.next_rising(s))) sunrise = sunrise.split(' ') sunrise = sunrise[1].split(":") data['sr'] = sunrise[0]+":"+sunrise[1] if (int(sunrise[0])<13): sunrise[0] = str(int(sunrise[0])) sunrise[2] = 'AM' else: sunrise[0] = str(int(sunrise[0])-12) sunrise[2] = 'PM' sunset = str(ephem.localtime(o.next_setting(s))) sunset = sunset.split(' ') sunset = sunset[1].split(":") data['ss'] = sunset[0]+":"+sunset[1] if (int(sunset[0])<13): sunset[0] = str(int(sunrise[0])) sunset[2] = 'AM' else: sunset[0] = str(int(sunset[0])-12) sunset[2] = 'PM' srise = sunrise[0]+":"+sunrise[1]+" "+sunrise[2] sset = sunset[0]+":"+sunset[1]+" "+sunset[2] data['sunrise'] = srise data['sunset'] = sset return data
phasepath = "/home/nikospag/.cache/conky/phase.png" #Output image file path textpath = "/home/nikospag/.cache/conky/moon.txt" # Output text file path m = ephem.Moon() s = ephem.Sun() m.compute() s.compute() sun_glon = ephem.degrees(s.hlon + math.pi).norm moon_glon = m.hlon age = ephem.degrees(moon_glon - sun_glon).norm age = age / (2 * math.pi) * 100 au = ephem.meters_per_au m_au = m.earth_distance dist = m_au * au / 1000 #Moon distance in Km a = m.elong dt = ephem.next_full_moon(ephem.now()) dtlocal = ephem.localtime(dt) fullmoon = dtlocal.strftime('%d %b, %H:%M') phase = m.moon_phase illum = phase * 100 phase = 1 - phase if a > 0: phase = -phase #Draw phase shade on input moon image and save with Image(filename=moonpath) as img: radius = img.height // 2 with Drawing() as draw: draw.fill_color = Color("rgba(0, 0, 0, 0.7)") if phase < 0: phase = abs(phase) for y in range(radius):
def friendlydate(d): lt = ephem.localtime(d) return lt.strftime("%b %d")
def getTimes(sun): # calculate previous and next sunrise and sunset times r1 = home.previous_rising(sun) r2 = home.next_rising(sun) s1 = home.previous_setting(sun) s2 = home.next_setting(sun) # calculate prev/next sunrise/sunset and tNow pSunrise = ephem.Date(ephem.localtime(r1)) nSunrise = ephem.Date(ephem.localtime(r2)) pSunset = ephem.Date(ephem.localtime(s1)) nSunset = ephem.Date(ephem.localtime(s2)) tNow = ephem.Date(ephem.localtime(home.date)) # calculate tOpen and tClose based on which side of midnight we are on and any offsets if (tNow > pSunset and tNow.tuple()[2] == pSunset.tuple()[2]): logger.debug( "in branch tNow > pSunset and tNow.tuple()[2] == pSunset.tuple()[2], AE" ) # tNow and pSunset are on the same day, so we're after sunset before midnight # this is either scenario A or E tOpen = ephem.Date( ephem.localtime(ephem.Date(r1 - c_offset * ephem.minute))) tClose = ephem.Date( ephem.localtime(ephem.Date(s1 + c_offset * ephem.minute))) elif (tNow <= nSunset and tNow.tuple()[2] == nSunset.tuple()[2]): # tNow and nSunset are on the same day # this is either scenario B, C, or D logger.debug( "tNow <= nSunset and tNow.tuple()[2] == nSunset.tuple()[2], BCD") # tClose is always based on nSunset tClose = ephem.Date( ephem.localtime(ephem.Date(s2 + c_offset * ephem.minute))) # tOpen calculates with nSunrise until nSunrise passes, then calculate with pSunrise # the scenario C vs D math gets sorted out at the main program by comparing tNow with tOpen and tClose if (tNow < nSunrise and tNow.tuple()[2] == nSunrise.tuple()[2]): logger.debug( "tNow < nSunrise and tNow.tuple()[2] == nSunrise.tuple()[2], scenario B or C" ) tOpen = ephem.Date( ephem.localtime(ephem.Date(r2 - c_offset * ephem.minute))) else: logger.debug( "tNow not less than nSunrise and not on same day as nSunrise, scenario C or D" ) tOpen = ephem.Date( ephem.localtime(ephem.Date(r1 - c_offset * ephem.minute))) else: # something bad happened, so set nonsense values that make the door shut logger.debug("something wacky is happening, check 'er out") tClose = pSunrise tOpen = nSunset # debug logger.debug("pSunrise %s", pSunrise) logger.debug("pSunset %s", pSunset) logger.debug("nSunrise %s", nSunrise) logger.debug("nSunset %s", nSunset) logger.debug("tOpen %s", tOpen) logger.debug("tClose %s", tClose) logger.debug("tNow %s", tNow) return tNow, tOpen, tClose
def test_localtime_modern(self): if time.timezone == 18000: # test only works in Eastern time zone self.assertEqual(localtime(Date('2009/6/23 8:47')), datetime(2009, 6, 23, 4, 47, 0))
def getweatherdata(dsd): """Return current weather data in a structure weather.py expects""" mintemps = [999, 999, 999, 999, 999, 999, 999] maxtemps = [-999, -999, -999, -999, -999, -999, -999] weathers = ["NA", "NA", "NA", "NA", "NA", "NA", "NA"] fcicons = ["NA", "NA", "NA", "NA", "NA", "NA", "NA"] wind_directions = [ "N", "NNE", "NE", "ENE", "E", "ESE", "SE", "SSE", "S", "SSW", "SW", "WSW", "W", "WNW", "NW", "NNW" ] daynames = [ "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday" ] try: status = 0 pman = urllib3.PoolManager() urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) ret = pman.request( 'GET', 'https://api.darksky.net/forecast/' + DS_API_KEY + '/' + DS_LAT + ',' + DS_LON + '?EXCLUDE=[minutely,hourly]') status = 1 curr = json.loads(ret.data.decode('utf-8')) dsd['observation_time'] = str( datetime.datetime.fromtimestamp( curr['currently']['time']).strftime('Upd: %Y-%m-%d %H:%M:%S')) dsd['weather'] = curr['currently']['summary'] dsd['temp_f'] = int(round(curr['currently']['temperature'], 0)) dsd['relative_humidity'] = str(int(curr['currently']['humidity'] * 100)) dsd['wind_dir'] = wind_directions[int( ((curr['currently']['windBearing'] / 22.5) + .5) % 16)] dsd['wind_mph'] = curr['currently']['windSpeed'] dsd['wind_gust_mph'] = curr['currently'].get('windGust', 0) dsd['pressure_in'] = str( round(curr['currently']['pressure'] / 33.8639, 2)) dsd['windchill'] = curr['currently']['apparentTemperature'] dsd['visibility_mi'] = curr['currently'].get('visibility', 0) # dsd['precip_today_in'] = 0 #### Fix this! status = 2 i = 0 dsd['fctxt'] = [ dict(), dict(), dict(), dict(), dict(), dict(), dict(), dict() ] today = datetime.datetime.today() for fcperiod in curr['daily']['data']: fcday = datetime.datetime.fromtimestamp(fcperiod['time']) index = fcday.weekday() mintemps[index] = fcperiod['temperatureMin'] maxtemps[index] = fcperiod['temperatureMax'] weathers[index] = fcperiod['icon'] if weathers[index].startswith('partly-cloudy'): weathers[index] = 'partly cloudy' if weathers[index].startswith('clear'): weathers[index] = 'clear' fcicons[index] = fcperiod['icon'] dsd['fctxt'][i]['fcttext'] = fcperiod['summary'] wg_trace_print( "Weekday = " + str(index) + ", mintemp = " + str(mintemps[index]) + ", maxtemp = " + str(maxtemps[index]) + ", weather = " + weathers[index], TRACE) i = i + 1 if i > 3: break i = 0 day = today.weekday() dsd['fc'] = [dict(), dict(), dict(), dict()] while True: dsd['fc'][i] = dict() dsd['fc'][i]['name'] = daynames[day] dsd['fc'][i]['high_f'] = str(int(round(maxtemps[day], 0))) + "°F" dsd['fc'][i]['low_f'] = str(int(round(mintemps[day], 0))) + "°F" dsd['fc'][i]['icon'] = weathers[day] dsd['fc'][i]['icon_url'] = fcicons[day] + ".gif" day = day + 1 if day > 6: day = 0 i = i + 1 if i > 3: break status = 3 dsd['sunrise'] = str( datetime.datetime.fromtimestamp( curr['daily']['data'][0]['sunriseTime']).strftime('%I:%M %p')) dsd['sunset'] = str( datetime.datetime.fromtimestamp( curr['daily']['data'][0]['sunsetTime']).strftime('%I:%M %p')) status = 4 dsd['ageOfMoon'] = int( round(28 * curr['daily']['data'][0]['moonPhase'], 0)) status = 5 risetime = ["0", "0"] settime = ["0", "0"] ephem.Moon() obs_loc = ephem.Observer() obs_loc.lat = DS_LAT obs_loc.lon = DS_LON obs_loc.date = datetime.datetime.utcnow() moon_rise = ephem.localtime(obs_loc.next_rising(ephem.Moon())) if moon_rise.day == datetime.datetime.now().day: risetime = (str(ephem.localtime(obs_loc.next_rising( ephem.Moon()))).split(' ')[1].split(':')) else: moon_rise = ephem.localtime(obs_loc.previous_rising(ephem.Moon())) if moon_rise.day == datetime.datetime.now().day: risetime = (str( ephem.localtime(obs_loc.previous_rising( ephem.Moon()))).split(' ')[1].split(':')) else: risetime = "NA" moon_set = ephem.localtime(obs_loc.next_setting(ephem.Moon())) if moon_set.day == datetime.datetime.now().day: settime = (str(ephem.localtime(obs_loc.next_setting( ephem.Moon()))).split(' ')[1].split(':')) else: moon_set = ephem.localtime(obs_loc.previous_setting(ephem.Moon())) if moon_set.day == datetime.datetime.now().day: settime = (str( ephem.localtime(obs_loc.previous_setting( ephem.Moon()))).split(' ')[1].split(':')) else: settime = "NA" # wg_trace_print("moon rise " + str(risetime), True) if risetime != "NA": rtime = int(risetime[0]) if rtime >= 12: # after noon ampm = "PM" else: ampm = "AM" if rtime > 12: # after noon rtime = rtime - 12 elif rtime == 0: # midnight rtime = 12 dsd['moonrise'] = '%s:%s %s' % (rtime, risetime[1], ampm) else: dsd['moonrise'] = risetime # wg_trace_print("moon set " + str(settime), True) if settime != "NA": stime = int(settime[0]) if stime >= 12: stime = stime - 12 ampm = "PM" else: ampm = "AM" if stime > 12: # after noon stime = stime - 12 elif stime == 0: # midnight stime = 12 dsd['moonset'] = '%s:%s %s' % (stime, settime[1], ampm) else: dsd['moonset'] = settime status = 6 dsd['alerts'] = [] # Fix this! for alert in curr.get('alerts', []): dsd['alerts'].append(alert['description']) return True except: wg_error_print( "GetWeatherData", "Weather Collection Error #1 (status = " + str(status) + ") " + "(Exc type = " + str(sys.exc_info()[0]) + ") " + "(Exc value = " + str(sys.exc_info()[1]) + ")") return False
#!/usr/bin/python import argparse import datetime import ephem parser = argparse.ArgumentParser( 'Output the time of the next sunset in HH:MM format.') parser.add_argument('--offsetmins', dest='offsetmins', help='apply an offset in minutes to the time output') args = parser.parse_args() # Denver observer = ephem.Observer() observer.lat = '39.7392' observer.lon = '-104.9903' observer.elevation = 5280 sun = ephem.Sun() # Python datetime object sunset = ephem.localtime(observer.next_setting(sun)) # Apply offset if provided if (args.offsetmins): sunset += datetime.timedelta(minutes=int(args.offsetmins)) print sunset.strftime("%H:%M")
import ephem import datetime tokyo = ephem.city('Tokyo') tokyo.date = datetime.datetime.utcnow() sun = ephem.Sun() print("次の東京の日の出時刻: ", ephem.localtime(tokyo.next_rising(sun))) print("次の東京の日の入り時刻: ", ephem.localtime(tokyo.next_setting(sun)))
def astro_planetnexttransit(planet): location = astro_obslocation("OULLINS") eventdate = ephem.localtime( ephem.Date(location.next_transit(astro_ephemplanet(planet)))) location.date = datetime.datetime.utcnow() return "TR: " + eventdate.strftime('%b %d %H:%M:%S')
def astro_planetnextsetting(planet): location = astro_obslocation("OULLINS") eventdate = ephem.localtime( ephem.Date(location.next_setting(astro_ephemplanet(planet)))) return "S: " + eventdate.strftime('%b %d %H:%M') location.date = datetime.datetime.utcnow()
ocol = "${color #999999}" elif oblak == "Небольшой дождь": ocol = "${color #cyan}" elif oblak == "Дождь": ocol = "${color #cyan}" else: ocol = "${color #cyan}" #--------------------------------------------------------- obs = ephem.Observer() sun = ephem.Sun() obs.lat = lat obs.long = lng obs.date = datetime.datetime.today() rise_time = obs.next_rising(sun) set_time = obs.next_setting(sun) sunrise = ephem.localtime(rise_time).strftime('%H:%M') sunset = ephem.localtime(set_time).strftime('%H:%M') moon = ephem.Moon() m_rise_time = obs.next_rising(moon) m_set_time = obs.next_setting(moon) moonrise = ephem.localtime(m_rise_time).strftime('%H:%M') moonset = ephem.localtime(m_set_time).strftime('%H:%M') '''if int(sredn) > 0: temp = "+" + str(sredn) else: temp = str(sredn)''' if int(sredn) > 0.1: temp = "+" + str(sredn) temp_color = "${color red}" else:
logLine = "Starting the skycam with a cadence of %d seconds" % cadence log.info(logLine) sun = ephem.Sun() meteoLocation = ephem.Observer() #meteoLocation.lon = '-3.5262707' #meteoLocation.lat = '40.3719808' #meteoLocation.elevation = 900 #meteoLocation.lon = '342.12' # meteoLocation.lat = '28.76' meteoLocation.elevation = 2326 meteoLocation.lon = '-17.7742491' meteoLocation.lat = '28.6468866' #meteoLocation.elevation = 281 d = datetime.datetime.utcnow() localTime = ephem.localtime(ephem.Date(d)) print(localTime) meteoLocation.date = ephem.Date(d) sun = ephem.Sun(meteoLocation) while True: # Get the sun's current altitude night = False d = datetime.datetime.utcnow() meteoLocation.date = ephem.Date(d) sun = ephem.Sun(meteoLocation) print(sun.az, sun.alt) altitude = sun.alt * 180 / 3.14125 if args.service: log.info("Sun altitude is: %.2f\n" % altitude) else:
def onHeartbeat(self): Domoticz.Debug("onHeartbeat") self.__runAgain -= 1 if self.__runAgain <= 0: self.__runAgain = self.__HEARTBEATS2MIN * self.__MINUTES # utc_now = datetime.datetime.utcnow() target_date = datetime.datetime.now().date() # self.__observer.date = utc_now self.__sun.compute(self.__observer) # ################################################################################ # Sun data ################################################################################ # # ------------------------------------------------------------------------------- # Sun altitude # ------------------------------------------------------------------------------- value = round(deg(self.__sun.alt), 2) UpdateDevice(unit.SUN_ALT, int(value), str(value)) # # ------------------------------------------------------------------------------- # Sun azimuth # ------------------------------------------------------------------------------- value = round(deg(self.__sun.az), 2) UpdateDevice(unit.SUN_AZ, int(value), str(value)) # # ------------------------------------------------------------------------------- # Sun distance # ------------------------------------------------------------------------------- value = round(self.__sun.earth_distance * ephem.meters_per_au / 1000) UpdateDevice(unit.SUN_DIST, int(value), str(value)) # # ------------------------------------------------------------------------------- # Sun transit # ------------------------------------------------------------------------------- value = ( ephem.localtime(self.__observer.next_transit(self.__sun)) + self.__SEC30 ) UpdateDevice( unit.SUN_TRANSIT, 0, "{}".format(value.strftime(self.__DT_FORMAT)) ) # # ------------------------------------------------------------------------------- # Sun rise & set today # ------------------------------------------------------------------------------- self.__observer.date = target_date self.__sun.compute(self.__observer) i = 0 for t in self.__TWILIGHTS: # Zero the horizon self.__observer.horizon = t[0] try: next_rising = ( ephem.localtime( self.__observer.next_rising(self.__sun, use_center=t[1]) ) + self.__SEC30 ) UpdateDevice( unit.SUN_RISE + i, 0, "{}".format(next_rising.strftime(self.__DT_FORMAT)), ) except: UpdateDevice( unit.SUN_RISE + i, 0, "{}".format("No time available"), ) try: next_setting = ( ephem.localtime( self.__observer.next_setting(self.__sun, use_center=t[1]) ) + self.__SEC30 ) UpdateDevice( unit.SUN_SET + i, 0, "{}".format(next_setting.strftime(self.__DT_FORMAT)), ) except: UpdateDevice( unit.SUN_RISE + i, 0, "{}".format("No time available"), ) if i == 0: value = (next_setting - next_rising).total_seconds() hh = divmod(value, 3600) mm = divmod(hh[1], 60) min = int(divmod(value, 60)[0]) UpdateDevice( unit.DAY_LENGTH_M, min, "{}".format(min), ) UpdateDevice( unit.DAY_LENGTH_T, 0, "{:02}:{:02}".format(int(hh[0]), int(mm[0])), ) i += 1 # # Reset horizon for further calculations self.__observer.horizon = "0" # ################################################################################ # Moon data ################################################################################ # self.__observer.date = utc_now self.__moon.compute(self.__observer) # # ------------------------------------------------------------------------------- # Moon rise # ------------------------------------------------------------------------------- value = ( ephem.localtime(self.__observer.next_rising(self.__moon)) + self.__SEC30 ) UpdateDevice( unit.MOON_RISE, 0, "{}".format(value.strftime(self.__DT_FORMAT)) ) # # ------------------------------------------------------------------------------- # Moon set # ------------------------------------------------------------------------------- value = ( ephem.localtime(self.__observer.next_setting(self.__moon)) + self.__SEC30 ) UpdateDevice( unit.MOON_SET, 0, "{}".format(value.strftime(self.__DT_FORMAT)) ) # # ------------------------------------------------------------------------------- # Moon altitude # ------------------------------------------------------------------------------- self.__moon.compute(self.__observer) # value = round(deg(self.__moon.alt), 2) UpdateDevice(unit.MOON_ALT, int(value), str(value)) # # ------------------------------------------------------------------------------- # Moon azimuth # ------------------------------------------------------------------------------- value = round(deg(self.__moon.az), 2) UpdateDevice(unit.MOON_AZ, int(value), str(value)) # # ------------------------------------------------------------------------------- # Moon distance # ------------------------------------------------------------------------------- value = round(self.__moon.earth_distance * ephem.meters_per_au / 1000) UpdateDevice(unit.MOON_DIST, int(value), str(value)) # # ------------------------------------------------------------------------------- # Next new moon # ------------------------------------------------------------------------------- next_new = ephem.localtime(ephem.next_new_moon(utc_now)) value = next_new + self.__SEC30 UpdateDevice( unit.MOON_NEXT_NEW, 0, "{}".format(value.strftime(self.__DT_FORMAT)) ) # # ------------------------------------------------------------------------------- # Next first quarter # ------------------------------------------------------------------------------- next_first_quarter = ephem.localtime(ephem.next_first_quarter_moon(utc_now)) value = next_first_quarter + self.__SEC30 UpdateDevice( unit.MOON_NEXT_FIRST_QUARTER, 0, "{}".format(value.strftime(self.__DT_FORMAT)), ) # # ------------------------------------------------------------------------------- # Next full moon # ------------------------------------------------------------------------------- next_full = ephem.localtime(ephem.next_full_moon(utc_now)) value = next_full + self.__SEC30 UpdateDevice( unit.MOON_NEXT_FULL, 0, "{}".format(value.strftime(self.__DT_FORMAT)), ) # # ------------------------------------------------------------------------------- # Next last quarter # ------------------------------------------------------------------------------- next_last_quarter = ephem.localtime(ephem.next_last_quarter_moon(utc_now)) value = next_last_quarter + self.__SEC30 UpdateDevice( unit.MOON_NEXT_LAST_QUARTER, 0, "{}".format(value.strftime(self.__DT_FORMAT)), ) # # ------------------------------------------------------------------------------- # Moon phase # ------------------------------------------------------------------------------- next_full = next_full.date() next_new = next_new.date() next_last_quarter = next_last_quarter.date() next_first_quarter = next_first_quarter.date() previous_full = ephem.localtime(ephem.previous_full_moon(utc_now)).date() previous_new = ephem.localtime(ephem.previous_new_moon(utc_now)).date() previous_last_quarter = ephem.localtime( ephem.previous_last_quarter_moon(utc_now) ).date() previous_first_quarter = ephem.localtime( ephem.previous_first_quarter_moon(utc_now) ).date() # # Domoticz.Debug("target_date: {}".format(target_date)) # Domoticz.Debug("next_full: {}".format(next_full)) # Domoticz.Debug("next_new: {}".format(next_new)) # Domoticz.Debug("next_last_quarter: {}".format(next_last_quarter)) # Domoticz.Debug("next_first_quarter: {}".format(next_first_quarter)) # Domoticz.Debug("previous_full: {}".format(previous_full)) # Domoticz.Debug("previous_new: {}".format(previous_new)) # Domoticz.Debug("previous_last_quarter: {}".format(previous_last_quarter)) # Domoticz.Debug("previous_first_quarter: {}".format(previous_first_quarter)) if target_date in (next_new, previous_new): phase = 0 elif target_date in (next_first_quarter, previous_first_quarter): phase = 2 elif target_date in (next_full, previous_full): phase = 4 elif target_date in (next_last_quarter, previous_last_quarter): phase = 6 elif ( previous_new < next_first_quarter < next_full < next_last_quarter < next_new ): phase = 1 elif ( previous_first_quarter < next_full < next_last_quarter < next_new < next_first_quarter ): phase = 3 elif ( previous_full < next_last_quarter < next_new < next_first_quarter < next_full ): phase = 5 elif ( previous_last_quarter < next_new < next_first_quarter < next_full < next_last_quarter ): phase = 7 else: phase = 4 UpdateDevice(unit.MOON_PHASE, 0, self.__MOON_PHASE_DESCRIPTIONS[phase]) UpdateDeviceImage( unit.MOON_PHASE, images.PREFIX_IMAGE + images.PREFIX_PHASE + str(phase) ) # self.__moon.compute(self.__observer) # # ------------------------------------------------------------------------------- # Moon illumination # ------------------------------------------------------------------------------- value = round(deg(self.__moon.moon_phase), 2) UpdateDevice(unit.MOON_ILLUMINATION, int(value), str(value)) UpdateDeviceImage( unit.MOON_ILLUMINATION, images.PREFIX_IMAGE + images.PREFIX_PHASE + str(phase), ) # else: Domoticz.Debug( "onHeartbeat called, run again in {} heartbeats.".format( self.__runAgain ) )
# Analemma computation physical_timezone_delta = datetime.timedelta(hours=(float(OBS.lon) * 12 / math.pi)) hour_o_clock = day.replace(tzinfo=None) \ + datetime.timedelta(hours=OBSERVATION_HOUR) \ - physical_timezone_delta OBS.date = hour_o_clock.strftime("%Y-%m-%d %H:%M:%S") SUN.compute(OBS) # AZIS.append(SUN.alt) # ALTS.append(SUN.az) # Ephemera calculation twelve_o_clock = day + datetime.timedelta(hours=12) # Set observer to 12:00 of day (in UTC) OBS.date = (twelve_o_clock).astimezone(pytz.utc).strftime("%Y-%m-%d %H:%M:%S") # Get sunrise/sunset in observer timezone sunrise = ephem.localtime(OBS.previous_rising(ephem.Sun())).astimezone(OBSERVER_TIMEZONE) sunset = ephem.localtime(OBS.next_setting(ephem.Sun())).astimezone(OBSERVER_TIMEZONE) # Get beginning/ending of day in observer timezone (needs to be re-localized after combining) beg_of_day = OBSERVER_TIMEZONE.localize(datetime.datetime.combine(day, datetime.time.min)) end_of_day = OBSERVER_TIMEZONE.localize(datetime.datetime.combine(day, datetime.time.max)) # Get sunrise/sunset as fraction normalized to day length sunrise_frac = (sunrise - beg_of_day) / (end_of_day - beg_of_day) sunset_frac = (sunset - beg_of_day) / (end_of_day - beg_of_day) print( ("\\eph" + "{{{}}}" * 9).format( day.strftime("%-j"), # day.strftime("%Y-%m-%d"), "{0:.3f}".format(SUN.alt), "{0:.3f}".format((SUN.alt-MIN_ALT)/(MAX_ALT-MIN_ALT)), "{0:.3f}".format(SUN.az),
def getNextPasses(self): lines = [] for line in open( '/home/rasmus/catkin_ws/src/antenna_controller/tle/tle.txt', 'r').readlines(): lines.append(line) print("VAAAAAAAAAAAAATATATAAAA SIISA {}".format(lines)) all_passes = [] obs = ephem.Observer() obs.lat = '59.394870' obs.long = '24.661399' # obs.horizon = '10' satellite = ephem.readtle(lines[0], lines[1], lines[2]) satellite.compute(obs) current_sat_passes = [] while (len(all_passes) < 3): pass_parts = [] rise_time, rise_az, max_alt_time, max_alt, set_time, set_az = obs.next_pass( satellite) # print("PASSES {}, {}, {}".format(all_passes, max_alt, obs.date)) if (math.degrees(max_alt) < 0): obs.date = set_time + ephem.minute continue satellite_time = ephem.localtime(rise_time) if (rise_time > set_time): range_s = satellite.range sat_az = math.degrees(satellite.az) sat_alt = math.degrees(satellite.alt) print( "CURRENT PASS : rise_time: {}, set_time: {}, current_time: {}, range: {}, az: {}, alt: {}" .format(rise_time, set_time, datetime.now().strftime("%d-%m-%Y %H:%M:%S"), range_s, sat_az, sat_alt)) turning_time = self.getTurningTime( sat_az, sat_alt) # Hetkel ei tee veel midagi, # kuid hiljem loeb antenni asukohta ja arvutab, kaua aega l'heks antenni pooramiseni ja paneb selle aja rise_timele juurde. # See t'hendab, et kui programm naeb, et antenn ei joua kuidagi moodi isegi mootma hakata, siis ei hakka ta seda satelliiti # uldse jalgima. rise_time = ephem.Date( ephem.Date(datetime.utcnow()) + ephem.second * 10) print("{}, | {}".format(rise_time, set_time)) if (rise_time > set_time): obs.date = set_time + ephem.minute continue while (rise_time < set_time): obs.date = rise_time satellite.compute(obs) pass_parts.append( (rise_time, math.radians(math.degrees(satellite.alt)), math.radians(math.degrees(satellite.az)), lines[0], int(lines[2].split(" ")[1]))) rise_time = ephem.Date(rise_time + ephem.second) all_passes.append(pass_parts) obs.date = rise_time + ephem.minute print("ALL PASSES LENGTH: {}".format(len(all_passes))) for x in all_passes: if len(x) > 0: print(x[0]) self.passes = all_passes
print("Seconds since last TLE check: %s" % next_seconds) if (next_seconds > (20 * 60)): getTLE() pt = ct iss = ephem.readtle(glob_tle[0], glob_tle[1], glob_tle[2]) site = ephem.Observer() site.date = datetime.datetime.utcnow() site.lat = str(LAT) site.lon = str(LON) site.horizon = str(HOR) site.elevation = ELV site.pressure = 0 print "Current UTC time : %s" % site.date print "Current Local time: %s" % ephem.localtime(site.date) # FIND NEXT PASS INFO JUST FOR REFERENCE tr, azr, tt, altt, ts, azs = site.next_pass(iss) duration = int((ts - tr) * 60 * 60 * 24) print("Next Pass (Localtime): %s" % ephem.localtime(tr)) if INFO: print("UTC Rise Time : %s" % tr) print("UTC Max Alt Time: %s" % tt) print("UTC Set Time : %s" % ts) print("Rise Azimuth: %s" % azr) print("Set Azimuth : %s" % azs) print("Max Altitude: %s" % altt) print("Duration : %s" % duration)
MYSQL_DB = "Digitemp" MYSQL_USER = "******" MYSQL_PASSWD = "Digitemp" MYSQL_TBL_SENSOR = "DigiTable" MYSQL_TBL_TEMP = "OutTemp" max_file = "/tmp/gnuplot-data-max.dat" min_file = "/tmp/gnuplot-data-min.dat" srise_file = "/tmp/gnuplot-data-srise.dat" sset_file = "/tmp/gnuplot-data-sset.dat" # lets work out the previous Sun Set and Sun Rise: o = ephem.Observer() o.lat, o.long, o.date = '22:12', '65:59', datetime.datetime.utcnow() sun = ephem.Sun(o) SRISE = ephem.localtime(o.previous_rising(sun)) SSET = ephem.localtime(o.previous_setting(sun)) # Setup data files, set number of samples == no of days. file = "/home/arne/Digilinus/SQLData/sqldata_last_period.dat" Data_Limit = 100 # = 10 days; 30 min per sample, so 48 per day. 30 days = 1440, 1 year = 17520 # First need to query the DB for a list of sensor names and compare with what we actually have on the network try: con = mdb.connect(MYSQL_HOST, MYSQL_USER, MYSQL_PASSWD, MYSQL_DB) cur = con.cursor() #print"Database opened ok" # go get around days worth of temperature records cur.execute( """SELECT DTimeStamp,OutTemp, InTemp FROM DigiTable order by DTimeStamp desc limit %s""", Data_Limit) f = open(file, 'w')
#!/usr/bin/python3 # Name: ephemeris # Author: sifan # Version: 20210410 # Desc: Calculates and html formats daily positions import ephem from datetime import datetime from dateutil import tz utc = datetime.utcnow() ko = ephem.Observer() ko.lon = '-124.040438' ko.lat = '44.867813' ko.elevation = 16 ko.epoch = '2021' ko.date = ephem.now() moon = ephem.Moon(ko) sun = ephem.Sun(ko) ko.pressure = 0 ko.horizon = '-12' # nautical twilight print("Sun Nautical Evening: %s, Morning: %s" % (ephem.localtime(ko.next_setting(sun, use_center=True)).ctime(), ephem.localtime(ko.next_rising(sun, use_center=True)).ctime())) print(" Moon Rise: %s, Set: %s, Percent: %d%%" % (ephem.localtime(ko.next_rising(moon)).ctime(), ephem.localtime(ko.next_setting(moon)).ctime(), moon.phase))
def tle_date_to_datetime(tle): return ephem.localtime(tle._epoch)
def main(): """ main method """ usage = "Example: python grid_obs_calculate.py -g G0008 " parser = OptionParser(usage, version=__version__) #"test")# __version__ ) parser.add_option( "-g", "--gridid", dest = "gridid" , type = "string", \ help = "Grid ID, default=G0001",default="G0001") opts, args = parser.parse_args() if len(sys.argv) == 1: print "please use -h to see help" print usage sys.exit() GridID = opts.gridid homedir = os.getcwd() configuration_file = './configuration.dat' configuration_file_dev = open(configuration_file, 'rU') lines1 = configuration_file_dev.read().splitlines() configuration_file_dev.close() for line1 in lines1: word = line1.split() if word[0] == 'griduser': griduser = word[2] elif word[0] == 'gridip': gridip = word[2] elif word[0] == 'gridmypassword': gridmypassword = word[2] elif word[0] == 'gridmydb': gridmydb = word[2] conf_obs_parameters_sys = './conf_obs_parameters_sys.dat' conf_obs_parameters_sys_dev = open(conf_obs_parameters_sys, 'rU') lines2 = conf_obs_parameters_sys_dev.read().splitlines() conf_obs_parameters_sys_dev.close() for line2 in lines2: word = line2.split() if word[0] == 'observatory_lat': observatory_lat = word[2] elif word[0] == 'observatory_lon': observatory_lon = word[2] elif word[0] == 'observatory_elevation': observatory_elevation = float(word[2]) elif word[0] == 'zenith_sun_min': zenith_sun_min = float(word[2]) elif word[0] == 'zenith_min': zenith_min = float(word[2]) elif word[0] == 'gal_min': gal_min = float(word[2]) elif word[0] == 'moon_dis_min_para': moon_dis_min_str = word[2] moon_dis_para_str = moon_dis_min_str.split('|') moon_dis_phase_data = [[]] for moon_dis_para in moon_dis_para_str: moon_dis_para_phase_min = float( moon_dis_para.split(':')[0].split('-')[0]) moon_dis_para_phase_max = float( moon_dis_para.split(':')[0].split('-')[1]) moon_dis_para_dis = float(moon_dis_para.split(':')[1]) moon_dis_phase_data.append([ moon_dis_para_phase_min, moon_dis_para_phase_max, moon_dis_para_dis ]) moon_dis_phase_data = filter(None, moon_dis_phase_data) conn_gwacoc_grid = MySQLdb.connect(host=gridip, user=griduser, passwd=gridmypassword, db=gridmydb) cursor_gwacoc_grid = conn_gwacoc_grid.cursor() grid_cmd = "select * from Grid_table where GridID = '" + GridID + "'" #print grid_cmd cursor_gwacoc_grid.execute(grid_cmd) extract_grid_result = cursor_gwacoc_grid.fetchall() print extract_grid_result cursor_gwacoc_grid.close() # define grid date frame ---------------------------------------- gridframe = pd.DataFrame() if len(extract_grid_result) > 0: gridframe['obs_date'] = 0 gridframe['Grid_ID'] = zip(*extract_grid_result)[1] gridframe['field_ID'] = zip(*extract_grid_result)[2] gridframe['ra_center'] = zip(*extract_grid_result)[3] gridframe['dec_center'] = zip(*extract_grid_result)[4] gridframe['radeg_h1'] = zip(*extract_grid_result)[5] gridframe['decdeg_h1'] = zip(*extract_grid_result)[6] gridframe['radeg_h2'] = zip(*extract_grid_result)[7] gridframe['decdeg_h2'] = zip(*extract_grid_result)[8] gridframe['radeg_l1'] = zip(*extract_grid_result)[9] gridframe['decdeg_l1'] = zip(*extract_grid_result)[10] gridframe['radeg_l2'] = zip(*extract_grid_result)[11] gridframe['decdeg_l2'] = zip(*extract_grid_result)[12] gridframe['mjd_begin'] = 0 gridframe['mjd_end'] = 0 gridframe['local_time_begin'] = 0 gridframe['local_time_end'] = 0 gridframe['lst_begin'] = 0 gridframe['lst_end'] = 0 gridframe['solar_alt_begin'] = 0 gridframe['solar_alt_end'] = 0 gridframe['lunar_ra_begin'] = 0 gridframe['lunar_dec_begin'] = 0 gridframe['lunar_phase_begin'] = 0 gridframe['lunar_ra_end'] = 0 gridframe['lunar_dec_end'] = 0 gridframe['lunar_phase_end'] = 0 #path = '/Users/han/tmp_pool/gwac_dispatch/obs_skymap/' # set observation day ------------------------------------------------ current_utc_datetime = datetime.datetime.utcnow() Op_time = current_utc_datetime.strftime('%Y-%m-%d') Op_time = time.strptime(Op_time, "%Y-%m-%d") gcal_y = Op_time.tm_year gcal_m = Op_time.tm_mon gcal_d = Op_time.tm_mday MJD_newyear = gcal2jd(gcal_y, gcal_m, gcal_d)[1] MJD_current = MJD_newyear date_current = jd2gcal(2400000.5, MJD_current) calendar_d_lable = "%d_%d_%d" % (date_current[0], date_current[1], date_current[2]) calendar_d = "%d-%d-%d" % (date_current[0], date_current[1], date_current[2]) # start calculate observation sequence # time_interval = 40.0 # 2 munitues # night_number = 36 # every 2 munitues, 720 in total. time_interval = 5.0 # 2 munitues night_number = 288 # every 2 munitues, 720 in total. # set observatory parameters ---------------------------------------- observatory = ephem.Observer() observatory.lat = observatory_lat observatory.lon = observatory_lon observatory.elevation = observatory_elevation lat_dd = float(str(observatory.lat).split(":")[0])+\ float(str(observatory.lat).split(":")[1])/60.0+\ float(str(observatory.lat).split(":")[2])/3600.0 # define obs date frame ---------------------------------------- obsframe = pd.DataFrame() for k in range(len(gridframe['Grid_ID'])): #print 'field coor: ',gridframe['ra_center'][k],gridframe['dec_center'][k] mjd = [] local_time = [] lst = [] solar_alt = [] lunar_ra = [] lunar_dec = [] lunar_phase = [] gridframe.loc[k, 'obs_date'] = calendar_d # calculate galactic coordinate of field center and all vertexes coor_equ_cen = ephem.Equatorial(gridframe['ra_center'][k], gridframe['dec_center'][k], epoch='2000') g_cen = ephem.Galactic(coor_equ_cen) g_cen_lat_dd = float(str(g_cen.lat).split(":")[0])+\ float(str(g_cen.lat).split(":")[1])/60.0+\ float(str(g_cen.lat).split(":")[2])/3600.0 coor_equ_h1 = ephem.Equatorial(gridframe['radeg_h1'][k], gridframe['decdeg_h1'][k], epoch='2000') g_h1 = ephem.Galactic(coor_equ_h1) g_h1_lat_dd = float(str(g_h1.lat).split(":")[0])+\ float(str(g_h1.lat).split(":")[1])/60.0+\ float(str(g_h1.lat).split(":")[2])/3600.0 coor_equ_h2 = ephem.Equatorial(gridframe['radeg_h2'][k], gridframe['decdeg_h2'][k], epoch='2000') g_h2 = ephem.Galactic(coor_equ_h2) g_h2_lat_dd = float(str(g_h2.lat).split(":")[0])+\ float(str(g_h2.lat).split(":")[1])/60.0+\ float(str(g_h2.lat).split(":")[2])/3600.0 coor_equ_l1 = ephem.Equatorial(gridframe['radeg_l1'][k], gridframe['decdeg_l1'][k], epoch='2000') g_l1 = ephem.Galactic(coor_equ_l1) g_l1_lat_dd = float(str(g_l1.lat).split(":")[0])+\ float(str(g_l1.lat).split(":")[1])/60.0+\ float(str(g_l1.lat).split(":")[2])/3600.0 coor_equ_l2 = ephem.Equatorial(gridframe['radeg_l2'][k], gridframe['decdeg_l2'][k], epoch='2000') g_l2 = ephem.Galactic(coor_equ_l2) g_l2_lat_dd = float(str(g_l2.lat).split(":")[0])+\ float(str(g_l2.lat).split(":")[1])/60.0+\ float(str(g_l2.lat).split(":")[2])/3600.0 galactic_lat_min = min([ abs(g_cen_lat_dd), abs(g_h1_lat_dd), abs(g_h2_lat_dd), abs(g_l1_lat_dd), abs(g_l2_lat_dd) ]) for n in range(night_number): # set mjd time ---------------------------------------- MJD_time = MJD_current + (n * time_interval / 60.0 / 24.0) nighttime_current = jd2gcal(2400000.5, MJD_time) hh = int(nighttime_current[3] * 24.0) mm = int((nighttime_current[3] * 24.0 - hh) * 60.0) ss = (((nighttime_current[3] * 24.0 - hh) * 60.0) - mm) * 60.0 hms = "%02d:%02d:%02d" % (hh, mm, ss) nighttime_current_cal = ( '%s/%s/%s %s' % (nighttime_current[0], nighttime_current[1], nighttime_current[2], hms)) nighttime_current_str = ( '%s/%s/%sT%s' % (nighttime_current[0], nighttime_current[1], nighttime_current[2], hms)) observatory.date = nighttime_current_cal # set local time ---------------------------------------- local_nighttime_current = ephem.localtime(observatory.date) local_nighttime_current_str = str(local_nighttime_current).replace( ' ', 'T')[0:22] # calculate local sidereal time ---------------------------------------- lst_dd = float(str(observatory.sidereal_time()).split(":")[0])* 15.0+\ float(str(observatory.sidereal_time()).split(":")[1])/60.0* 15.0+\ float(str(observatory.sidereal_time()).split(":")[2])/3600.0* 15.0 # calculate altitude angle or zenith angular distance of the sun --------------------------------- solar = ephem.Sun(observatory) solar_alt_dd = 90 - float(str(solar.alt).split(":")[0]) + float( str(solar.alt).split(":")[1]) / 60.0 + float( str(solar.alt).split(":")[2]) / 3600.0 #print('solar %s' % (solar_alt_dd)) lunar = ephem.Moon(observatory) lunar_ra_dd = float(str(lunar.ra).split(":")[0]) * 15.0 + float( str(lunar.ra).split(":")[1]) / 60.0 * 15.0 + float( str(lunar.ra).split(":")[2]) / 3600.0 * 15.0 lunar_dec_dd = float(str(lunar.dec).split(":")[0]) + float( str(lunar.dec).split(":")[1]) / 60.0 + float( str(lunar.dec).split(":")[2]) / 3600.0 #print('lunar %s %s %s' % (lunar_ra_dd, lunar_dec_dd, lunar.moon_phase)) # calculate zenith angular distance of field center and all vertexes zenith_ang_dis_cen_dd = angular_distance( gridframe['ra_center'][k], gridframe['dec_center'][k], lst_dd, lat_dd) # calculate angular distance between field center and all vertexes and moon moon_ang_dis_cen_dd = angular_distance(gridframe['ra_center'][k], gridframe['dec_center'][k], lunar_ra_dd, lunar_dec_dd) moon_ang_dis_h1_dd = angular_distance(gridframe['radeg_h1'][k], gridframe['decdeg_h1'][k], lunar_ra_dd, lunar_dec_dd) moon_ang_dis_h2_dd = angular_distance(gridframe['radeg_h2'][k], gridframe['decdeg_h2'][k], lunar_ra_dd, lunar_dec_dd) moon_ang_dis_l1_dd = angular_distance(gridframe['radeg_l1'][k], gridframe['decdeg_l1'][k], lunar_ra_dd, lunar_dec_dd) moon_ang_dis_l2_dd = angular_distance(gridframe['radeg_l2'][k], gridframe['decdeg_l2'][k], lunar_ra_dd, lunar_dec_dd) moon_ang_dis_min = min([ moon_ang_dis_cen_dd, moon_ang_dis_h1_dd, moon_ang_dis_h2_dd, moon_ang_dis_l1_dd, moon_ang_dis_l2_dd ]) # set mini distance from the moon for mm in range(len(moon_dis_phase_data)): if (lunar.moon_phase >= moon_dis_phase_data[mm][0] and lunar.moon_phase < moon_dis_phase_data[mm][1]): moon_dis_min = moon_dis_phase_data[mm][2] break #print lunar.moon_phase,moon_dis_min #print k,gridframe.loc[k,'field_ID'],zenith_ang_dis_cen_dd , zenith_min , galactic_lat_min , gal_min , moon_ang_dis_min , moon_dis_min if (solar_alt_dd > zenith_sun_min) and ( zenith_ang_dis_cen_dd < zenith_min ): # and galactic_lat_min > gal_min and moon_ang_dis_min > moon_dis_min ): # print 'mjd: ',MJD_current,MJD_time,nighttime_current # print 'zenith: ',gridframe['ra_center'][k], gridframe['dec_center'][k],lst_dd,lat_dd,solar_alt_dd,zenith_ang_dis_cen_dd,zenith_min mjd.append(MJD_time) local_time.append(local_nighttime_current_str) lst.append(lst_dd) solar_alt.append(solar_alt_dd) lunar_ra.append(lunar_ra_dd) lunar_dec.append(lunar_dec_dd) lunar_phase.append(lunar.moon_phase) #print gridframe['field_ID'],MJD_time # del mjd[0] # del local_time[0] # del lst[0] # del solar_alt[0] # del lunar_ra[0] # del lunar_dec[0] # del lunar_phase[0] # mjd = filter(None,mjd) # local_time = filter(None,local_time) # lst = filter(None,lst) # solar_alt = filter(None,solar_alt) # lunar_ra = filter(None,lunar_ra) # lunar_dec = filter(None,lunar_dec) # lunar_phase = filter(None,lunar_phase) if (len(mjd) > 0): obs_mjd_begin_index = 0 for mmm in range(len(mjd) - 1): m_gap = mjd[mmm + 1] - mjd[mmm] m_int = (2.0 / 24.0) if m_gap > m_int: obs_mjd_begin_index = mjd.index(mjd[mmm + 1]) if obs_mjd_begin_index == 0: obs_mjd_begin_index = mjd.index(min(mjd)) obs_mjd_end_index = mjd.index(max(mjd)) gridframe.loc[k, 'mjd_begin'] = mjd[obs_mjd_begin_index] gridframe.loc[k, 'mjd_end'] = mjd[obs_mjd_end_index] gridframe.loc[k, 'local_time_begin'] = local_time[obs_mjd_begin_index] gridframe.loc[k, 'local_time_end'] = local_time[obs_mjd_end_index] gridframe.loc[k, 'lst_begin'] = lst[obs_mjd_begin_index] gridframe.loc[k, 'lst_end'] = lst[obs_mjd_end_index] gridframe.loc[k, 'solar_alt_begin'] = solar_alt[obs_mjd_begin_index] gridframe.loc[k, 'solar_alt_end'] = solar_alt[obs_mjd_end_index] gridframe.loc[k, 'lunar_ra_begin'] = lunar_ra[obs_mjd_begin_index] gridframe.loc[k, 'lunar_dec_begin'] = lunar_dec[obs_mjd_end_index] gridframe.loc[ k, 'lunar_phase_begin'] = lunar_phase[obs_mjd_begin_index] gridframe.loc[k, 'lunar_ra_end'] = lunar_ra[obs_mjd_end_index] gridframe.loc[k, 'lunar_dec_end'] = lunar_dec[obs_mjd_begin_index] gridframe.loc[k, 'lunar_phase_end'] = lunar_phase[obs_mjd_end_index] for k in range(len(gridframe['obs_date'])): CurrentTable = "grid_observable_timetable" if gridframe.loc[k, 'mjd_begin'] > 0: insert_cmd = "insert into " + CurrentTable + " values ( DEFAULT , " + \ "'" + gridframe.loc[k,'obs_date'] + "' , " + \ "'" + gridframe.loc[k,'Grid_ID'] + "' , " + \ "'" + gridframe.loc[k,'field_ID'] + "' , " + \ " " + str(gridframe.loc[k,'ra_center']) + " , " + \ " " + str(gridframe.loc[k,'dec_center']) + " , " + \ " " + str(gridframe.loc[k,'radeg_h1']) + " , " + \ " " + str(gridframe.loc[k,'decdeg_h1']) + " , " + \ " " + str(gridframe.loc[k,'radeg_h2']) + " , " + \ " " + str(gridframe.loc[k,'decdeg_h2']) + " , " + \ " " + str(gridframe.loc[k,'radeg_l1']) + " , " + \ " " + str(gridframe.loc[k,'decdeg_l1']) + " , " + \ " " + str(gridframe.loc[k,'radeg_l2']) + " , " + \ " " + str(gridframe.loc[k,'decdeg_l2']) + " , " + \ " " + str(gridframe.loc[k,'mjd_begin']) + " , " + \ " " + str(gridframe.loc[k,'mjd_end']) + " , " + \ "'" + str(gridframe.loc[k,'local_time_begin']) + "' , " + \ "'" + str(gridframe.loc[k,'local_time_end']) + "' , " + \ " " + str(gridframe.loc[k,'lst_begin']) + " , " + \ " " + str(gridframe.loc[k,'lst_end']) + " , " + \ " " + str(gridframe.loc[k,'solar_alt_begin']) + " , " + \ " " + str(gridframe.loc[k,'solar_alt_end']) + " , " + \ " " + str(gridframe.loc[k,'lunar_ra_begin']) + " , " + \ " " + str(gridframe.loc[k,'lunar_dec_begin']) + " , " + \ " " + str(gridframe.loc[k,'lunar_phase_begin']) + " , " + \ " " + str(gridframe.loc[k,'lunar_ra_end']) + " , " + \ " " + str(gridframe.loc[k,'lunar_dec_end']) + " , " + \ " " + str(gridframe.loc[k,'lunar_phase_end']) + " " + \ " " + ")" print insert_cmd cursor = conn_gwacoc_grid.cursor() cursor.execute(insert_cmd) conn_gwacoc_grid.commit() cursor.close() conn_gwacoc_grid.close()
passes = [] logging.info('Starting monitor') while True: t = ephem.now() # calculate new passes if needed receiver.observer.date = t for sat in satellites: if t > sat.next_check_time: np = sat.next_pass(receiver.observer) if np.interesting: logging.info( '%s: interesting pass with TCA %s and max altitude %f, scheduling', sat, ephem.localtime(np.tca), np.max_elevation) passes.append(np) else: logging.debug('%s: ongoing or low pass with TCA %s, skipping', sat, ephem.localtime(np.tca)) sat.next_check_time = ephem.Date(np.end + ephem.minute) # handle scheduled or active passes for p in passes: if p.status == 'future': if t > p.begin: if receiver.running(): logging.info( '%s: raising, receiver busy, deferring reception', p.sat) p.set_status('deferred')
# UTC STRUCTURED DATE & TIME utc_hour = ephem.date.datetime(eos_time).strftime('%H') utc_minute = ephem.date.datetime(eos_time).strftime('%M') utc_second = ephem.date.datetime(eos_time).strftime('%S') utc_month = ephem.date.datetime(eos_time).strftime('%m') utc_day = ephem.date.datetime(eos_time).strftime('%d') utc_year = ephem.date.datetime(eos_time).strftime('%Y') utc_weekday = ephem.date.datetime(eos_time).strftime('%w') utc_dayyear = ephem.date.datetime(eos_time).strftime('%j') utc_weekyear = ephem.date.datetime(eos_time).strftime('%W') utc_lapd = ephem.date.datetime(eos_time).strftime('%x') utc_lapt = ephem.date.datetime(eos_time).strftime('%X') # LOCAL STRUCTURED DATE & TIME loc_hour = ephem.localtime(eos_time).strftime('%H') loc_minute = ephem.localtime(eos_time).strftime('%M') loc_second = ephem.localtime(eos_time).strftime('%S') loc_month = ephem.localtime(eos_time).strftime('%m') loc_day = ephem.localtime(eos_time).strftime('%d') loc_year = ephem.localtime(eos_time).strftime('%Y') loc_weekday = ephem.localtime(eos_time).strftime('%w') loc_dayyear = ephem.localtime(eos_time).strftime('%j') loc_weekyear = ephem.localtime(eos_time).strftime('%W') loc_lapd = ephem.localtime(eos_time).strftime('%x') loc_lapt = ephem.localtime(eos_time).strftime('%X') # WRITE FILE UTC HOUR file_utc_hour = open('/rex/data/ramdisk/sunset/utc_hour.txt', 'w') file_utc_hour.write((loc_hour)) file_utc_hour.close()
def setDate(self, date): self.here.date = ephem.date(date) + ephem.second * (self.exposure / 2) print ephem.localtime(self.here.date) print("Observer info: \n", self.here)
def OFF_test_localtime_premodern(self): if time.timezone == 18000: # test only works in Eastern time zone self.assertEqual(localtime(Date('1531/8/24 2:49')), datetime(1957, 10, 4, 15, 28, 34, 4))
def visit(events, observer): for self in events: date = self.getter(observer.date) if 0 <= date - observer.date < 1: return self, ephem.localtime(date) return (None, None)
def datestr(d): # The date may be wrong because of time zones. Convert to our timezone. lt = ephem.localtime(d) # return lt.strftime("%m/%d/%Y") return lt.strftime("%Y-%m-%d")
ds = ml.next_setting(sun) # azs = ml.sun.set_az up = (ds - dr) if up < 0: up += 1 uph = up * 24 h = int(uph) min = 60 * (uph - h) m = int(min) s = int(60 * (min - m)) up_text = '{:2d}:{:02d}:{:02d}'.format(h, m, s) chge = up - upp sign = "+" if chge < 0: sign = "-" chge *= -1 chgeh = chge * 24 ch = int(chgeh) chgem = 60 * (chgeh - ch) cm = int(chgem) cs = int(60 * (chgem - cm)) upp = up chge_text = '{:1d}:{:02d}'.format(cm, cs) rise_text = E.localtime(dr).strftime('%d %b %Y %H:%M:%S') # rise_az = set_text = E.localtime(ds).strftime('%H:%M:%S') print("%s %s %s %s%s" % (rise_text, set_text, up_text, sign, chge_text)) # print E.localtime(dr).strftime('%d %b %Y %H:%M:%S'), E.localtime(ds).strftime('%H:%M:%S') ml.date += 1
next_seconds = int((ct - pt).total_seconds()) if DEBUG: print(("Seconds since last TLE check: %s" % next_seconds)) if (next_seconds > (20 * 60)): getTLE() pt = ct iss = ephem.readtle(glob_tle[0], glob_tle[1], glob_tle[2]) site = ephem.Observer() site.date = datetime.datetime.utcnow() site.lat = str(LAT) site.lon = str(LON) site.horizon = str(HOR) site.elevation = ELV site.pressure = 0 lt = ephem.localtime(site.date) lt = lt.replace(microsecond=0) print("Current UTC time : %s" % site.date) print("Current Local time : %s" % lt) # FIND NEXT PASS INFO JUST FOR REFERENCE tr, azr, tt, altt, ts, azs = site.next_pass(iss) if (ts > tr): duration = int((ts - tr) * 60 * 60 * 24) lt = ephem.localtime(tr) lt = lt.replace(microsecond=0) print(("Next Pass Local time: %s" % lt)) print("") if INFO: print(("UTC Rise Time : %s" % tr))
import datetime import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D # 観測地設定 osaka = ephem.Observer() osaka.lat = '34.6914' osaka.lon = '135.4917' osaka.date = datetime.datetime.utcnow() # 月 moon = ephem.Moon() # 次回 月の出・月の入り等を表示 print("次の月の出 : ", ephem.localtime(osaka.next_rising(moon))) print("次の月の入り : ", ephem.localtime(osaka.next_setting(moon))) print("次の新月 : ", ephem.localtime(ephem.next_new_moon(osaka.date))) print("次の上弦 : ", ephem.localtime(ephem.next_first_quarter_moon(osaka.date))) print("次の満月 : ", ephem.localtime(ephem.next_full_moon(osaka.date))) print("次の下弦 : ", ephem.localtime(ephem.next_last_quarter_moon(osaka.date))) print("現在の月齢 : ", osaka.date - ephem.previous_new_moon(osaka.date)) # 月と太陽の離角を計算 moon.compute(osaka) moon_elong = np.rad2deg(moon.elong) # 描画領域を準備 fig = plt.figure(figsize=(5, 5)) ax = fig.gca(projection='3d')
def getNextSunrise(self, date): now = date.strftime("%Y/%m/%d %H:%M:%S") self.obs.date = now self.sun.compute() return ephem.localtime(self.obs.next_rising(self.sun))
moonrise = fred.next_rising(ephem.Moon()) moonset = fred.next_setting(ephem.Moon()) #We relocate the horizon to get twilight times fred.horizon = '-6' #-6=civil twilight, -12=nautical, -18=astronomical beg_twilight = fred.next_rising(ephem.Sun(), use_center=True) #Begin civil twilight end_twilight = fred.next_setting(ephem.Sun(), use_center=True) #End civil twilight fmt = "%H:%M" fmt2 = '%Y-%m-%d %H:%M:%S' # diese Variante Stimmt nicht !! print('Date and Time: {}'.format(dat.strftime(fmt2))) sr, ss = ephem.localtime(sunrise).strftime(fmt), ephem.localtime( sunset).strftime(fmt) print('%10s ▲%s ▼%s' % ('Sonne:', sr, ss)) bt, et = ephem.localtime(beg_twilight).strftime(fmt), ephem.localtime( end_twilight).strftime(fmt) print('%10s ▲%s ▼%s' % ('Dämmerung:', bt, et)) mr, ms = ephem.localtime(moonrise).strftime(fmt), ephem.localtime( moonset).strftime(fmt) print('%10s ▲%s ▼%s' % ('Mond:', mr, ms)) # correcte Variante !!! o = ephem.Observer() o.lat = '47.014956' o.long = '8.305175' o.elev = 446 o.pressure = 0