def __init__(self, year, timezone='Europe/Copenhagen', outformat='text'): """Compute moon phases for a whole year""" # Backtrack and look ahead to be sure to catch moons around newyear start_date = ephem.Date((year - 1, 9, 1)) end_date = ephem.Date((year + 1, 3, 1)) self.moon_phases = {} new_moon = ephem.next_new_moon(start_date) first_quarter = ephem.next_first_quarter_moon(start_date) full_moon = ephem.next_full_moon(start_date) last_quarter = ephem.next_last_quarter_moon(start_date) while True: local_new_moon = utc2localtime(new_moon.datetime()) local_first_quarter = utc2localtime(first_quarter.datetime()) local_full_moon = utc2localtime(full_moon.datetime()) local_last_quarter = utc2localtime(last_quarter.datetime()) if local_new_moon.year == year: self.moon_phases[local_new_moon] = \ self.moon_phase_names('new_moon', outformat) if local_first_quarter.year == year: self.moon_phases[local_first_quarter] = \ self.moon_phase_names('first_quarter', outformat) if local_full_moon.year == year: self.moon_phases[local_full_moon] = \ self.moon_phase_names('full_moon', outformat) if local_last_quarter.year == year: self.moon_phases[local_last_quarter] = \ self.moon_phase_names('last_quarter', outformat) new_moon = ephem.next_new_moon(new_moon) first_quarter = ephem.next_first_quarter_moon(first_quarter) full_moon = ephem.next_full_moon(full_moon) last_quarter = ephem.next_last_quarter_moon(last_quarter) if (new_moon > end_date) and (first_quarter > end_date) and \ (full_moon > end_date) and (last_quarter > end_date): break
def get_phase_name(location: Optional[ephem.Observer] = None, wiggle_room: float = 1.5) -> str: """Return name of the phase of the moon.""" if location: date = location.date else: date = ephem.now() if abs(ephem.next_first_quarter_moon(date) - date) < wiggle_room or \ abs(ephem.previous_first_quarter_moon(date) - date) < wiggle_room: return 'first quarter moon' elif abs(ephem.next_full_moon(date) - date) < wiggle_room or \ abs(ephem.previous_full_moon(date) - date) < wiggle_room: return 'full moon' elif abs(ephem.next_last_quarter_moon(date) - date) < wiggle_room or \ abs(ephem.previous_last_quarter_moon(date) - date) < wiggle_room: return 'last quarter moon' elif abs(ephem.next_new_moon(date) - date) < wiggle_room or \ abs(ephem.previous_new_moon(date) - date) < wiggle_room: return 'new moon' elif ephem.next_first_quarter_moon(date) - ephem.previous_new_moon(date) < 29: return 'waxing crescent' elif ephem.next_full_moon(date) - ephem.previous_first_quarter_moon(date) < 29: return 'waxing gibbous' elif ephem.next_last_quarter_moon(date) - ephem.previous_full_moon(date) < 29: return 'waning gibbous' elif ephem.next_new_moon(date) - ephem.previous_last_quarter_moon(date) < 29: return 'waning crescent' return ''
def phases(start): j = ephem.Moon() #start = '2015-10-1' moon_phases = {} for x in range(12): if x > 0: new_moon = ephem.next_new_moon(third_quarter) j.compute(new_moon) #print j.earth_distance * ephem.meters_per_au / 1000, j.phase else: year_c = str(start) new_moon = ephem.next_new_moon(year_c) first_quarter = ephem.next_first_quarter_moon(new_moon) full_moon = ephem.next_full_moon(first_quarter) # j = ephem.Moon() j.compute(full_moon) #print j.earth_distance * ephem.meters_per_au / 1000, j.phase third_quarter = ephem.next_last_quarter_moon(full_moon) moon_phases[x] = {'new moon' : str(new_moon), 'first quarter' : str(first_quarter), 'full moon' : str(full_moon), 'third quarter' : str(third_quarter)} #print 'New Moon :', new_moon #print 'First Quarter:', first_quarter #print 'Full Moon :', full_moon #print 'Third Quarter:', third_quarter #print '------------------------' #print moon_phases moon_phase_pd = pd.DataFrame(moon_phases)#, index=['new_moon', 'first_quarter', 'full_moon', 'third_quarter']) moon_phase_pd = moon_phase_pd.T #print moon_phase_pd moon_phase_pd.to_csv('astro/data/planet_stations/moon_phases.csv') return (moon_phases)
def astro_moonnextnew(DATETIME=None): if DATETIME == None: eventdate = ephem.localtime(ephem.next_new_moon(ephem.now())) return "FM: " + eventdate.strftime('%b %d %H:%M') else: return ephem.next_new_moon(DATETIME)
def phases(start): j = ephem.Moon() #start = '2015-10-1' moon_phases = {} for x in range(20): if x > 0: new_moon = ephem.next_new_moon(third_quarter) j.compute(new_moon) print j.earth_distance * ephem.meters_per_au / 1000, j.phase else: year_c = str(start) new_moon = ephem.next_new_moon(year_c) first_quarter = ephem.next_first_quarter_moon(new_moon) full_moon = ephem.next_full_moon(first_quarter) # j = ephem.Moon() j.compute(full_moon) print j.earth_distance * ephem.meters_per_au / 1000, j.phase third_quarter = ephem.next_last_quarter_moon(full_moon) moon_phases[x] = new_moon, first_quarter, full_moon, third_quarter print 'New Moon :', new_moon # print 'First Quarter:', first_quarter print 'Full Moon :', full_moon # print 'Third Quarter:', third_quarter #print '------------------------' #print moon_phases moon_phase_pd = pd.DataFrame(moon_phases)#, index=['new_moon', 'first_quarter', 'full_moon', 'third_quarter']) moon_phase_pd = moon_phase_pd.T print moon_phase_pd moon_phase_pd.to_csv('astro/data/planet_stations/moon_phases.csv') return (moon_phases)
def make_moon_stuff(outer_canv, inner_canv, begin_day, no_days, chart, obs): small_moon_rad = 0.12 large_moon_rad = 0.16 moon = ephem.Moon() moon2 = ephem.Moon() for doy in range(no_days) : obs.date = begin_day + doy mpc = obs.date + 0.5 # moon phase check moon_set = obs.next_setting(moon) moon2.compute(moon_set) X = moon2.moon_phase # Waxing moon (moonsets) x, y = to_chart_coord(moon_set, chart) if (fabs(ephem.next_full_moon(mpc) - mpc) < 0.5 or fabs(ephem.previous_full_moon(mpc) - mpc) < 0.5) : # full moon outer_canv.stroke(path.circle(x,y,large_moon_rad),[mooncolorlight,pyx.deco.filled([mooncolorlight])]) elif ((X < 0.55 and X > 0.45) or fabs(ephem.next_first_quarter_moon(mpc) - mpc) < 0.5 or fabs(ephem.previous_first_quarter_moon(mpc) - mpc) < 0.5) : # first quarter outer_canv.stroke(first_quarter_moon(large_moon_rad, x,y),[mooncolordark,pyx.deco.filled([mooncolordark])]) elif (fabs(ephem.next_new_moon(mpc) - mpc) < 0.5 or fabs(ephem.previous_new_moon(mpc) - mpc) < 0.5): # new moon outer_canv.stroke(path.circle(x,y,large_moon_rad),[mooncolorlight,pyx.deco.filled([mooncolordark])]) else : inner_canv.fill(waxing_moon(X, small_moon_rad, x, y), [style.linejoin.bevel,mooncolordark]) # Waning moon (moonrises) moon_rise = obs.next_rising(moon) moon2.compute(moon_rise) X = moon2.moon_phase x, y = to_chart_coord(moon_rise, chart) if (fabs(ephem.next_full_moon(mpc) - mpc) < 0.5 or fabs(ephem.previous_full_moon(mpc) - mpc) < 0.5) : # full moon outer_canv.stroke(path.circle(x,y,large_moon_rad),[mooncolorlight,pyx.deco.filled([mooncolorlight])]) elif ((X < 0.55 and X > 0.45) or fabs(ephem.next_last_quarter_moon(mpc) - mpc) < 0.5 or fabs(ephem.previous_last_quarter_moon(mpc) - mpc) < 0.5) : # last quarter outer_canv.stroke(last_quarter_moon(large_moon_rad, x,y),[mooncolorlight,pyx.deco.filled([mooncolorlight])]) elif (fabs(ephem.next_new_moon(mpc) - mpc) < 0.5 or fabs(ephem.previous_new_moon(mpc) - mpc) < 0.5): # new moon outer_canv.stroke(path.circle(x,y,large_moon_rad),[mooncolorlight,pyx.deco.filled([mooncolordark])]) else : inner_canv.fill(waning_moon(X, small_moon_rad, x, y), [style.linejoin.bevel,mooncolorlight])
def __init__(self, location, number): self.luneList = [] newMoon = ephem.next_new_moon(location.date) - 0.5 location.date = newMoon moon.compute(location) nextMonth = ephem.next_new_moon(location.date + 3) - 0.5 count = 0 while location.next_rising(moon) < nextMonth: count += 1 self.luneList.append(lune(location, number, count)) self.lunes = len(self.luneList) self.start = self.luneList[0].start self.end = self.luneList[-1].end self.number = number
def moon_age(now=None): if now is None: now = ephem.now() pmoon = ephem.previous_new_moon(now) nmoon = ephem.next_new_moon(now) deltamoon = nmoon - pmoon since_new = now - ephem.previous_new_moon(now) till_new = now - ephem.next_new_moon(now) print(since_new, deltamoon / 2.0) if since_new > deltamoon / 2.0: age = till_new else: age = since_new return age
def getSunMoon(locationInfo): night = False meteoLocation = ephem.Observer() meteoLocation.lon = str(locationInfo['longitude']) meteoLocation.lat = str(locationInfo['latitude']) meteoLocation.elevation = locationInfo['elevation'] d = datetime.datetime.utcnow() localTime = ephem.localtime(ephem.Date(d)) information("local time: " + str(localTime)) information("universal time: " + str(d)) meteoLocation.date = ephem.Date(d) sun = ephem.Sun(meteoLocation) moon = ephem.Moon(meteoLocation) # information("Sun azimuth: %s altitude: %s"%(sun.az, sun.alt)) altitude = sun.alt * 180 / 3.14125 information("Sun elevation is: %.2f" % altitude) currentDate = ephem.Date(d) timeToNewMoon = ephem.next_new_moon(currentDate) - currentDate timeSinceLastNewMoon = currentDate - ephem.previous_new_moon(currentDate) period = timeToNewMoon + timeSinceLastNewMoon phase = timeSinceLastNewMoon / period information("Moon elevation is: %.2f and illumination is: %.2f" % (moon.alt * 180 / 3.14125, moon.phase)) if altitude < -5: # information("will take night exposure...") night = True results = { "night": night, "sunElevation": altitude, "moonIllumination": moon.phase, "moonElevation": (moon.alt * 180 / 3.14125) } return results
def get_next_date_special(self, date_tuple, utc_offset=0): """ Returns next ephemeris date the given time. The date tuple should be in the local time. return date tupple """ cpm = None; if self.string_tab == '@fullmoon': cpm = ephem.next_full_moon(date_tuple) elif self.string_tab == '@newmoon': cpm = ephem.next_new_moon(date_tuple) elif self.string_tab == '@firstquarter': cpm = ephem.next_first_quarter_moon(date_tuple) elif self.string_tab == '@lastquarter': cpm = ephem.next_last_quarter_moon(date_tuple) elif self.string_tab == '@equinox': cpm = ephem.next_equinox(date_tuple) elif self.string_tab == '@solstice': cpm = ephem.next_solstice(date_tuple) elif self.string_tab in ['@dawn', '@dusk']: bobs = ephem.Sun() date = "{0}/{1}/{2}".format(date_tuple[0], date_tuple[1], date_tuple[2]) if self.string_tab == '@dawn': cpm = self._city.next_rising(bobs, start=date) else: cpm = self._city.next_setting(bobs, start=date) if cpm: return cpm.tuple()[:-1] return None
def lunarPhase(birth): ''' 'new moon':'🌑', 'crescent moon':'🌒', 'first quarter moon':'🌓', 'gibbous moon':'🌔', 'full moon':'🌕', 'disseminating moon':'🌖', 'last quarter moon':'🌗', 'balsamic moon':'🌘' ''' moon = ephem.Moon() moon.compute(birth) if moon.phase < 0.2: symbol = symbols['lunar phases']['new moon'] elif moon.phase > 99.8: symbol = symbols['lunar phases']['full moon'] else: if ephem.next_full_moon(birth.date) > ephem.next_new_moon(birth.date): #moon is waning if moon.phase < 33: symbol = symbols['lunar phases']['balsamic moon'] elif moon.phase < 66: symbol = symbols['lunar phases']['last quarter moon'] else: symbol = symbols['lunar phases']['disseminating moon'] else: #moon is waxing if moon.phase < 33: symbol = symbols['lunar phases']['crescent moon'] elif moon.phase < 66: symbol = symbols['lunar phases']['first quarter moon'] else: symbol = symbols['lunar phases']['gibbous moon'] return symbol
def moon_info(): "A bit more useful information about the Moon" now = ephem.now() previous_new = ephem.previous_new_moon(now) moon_age = 24 * (now - previous_new) if moon_age <= 72: yield "☽ Young Moon: {:.1f} hours".format(moon_age) else: next_new = ephem.next_new_moon(now) moon_age = 24 * (next_new - now) if moon_age <= 72: yield "☽ Old Moon {:.1f} hours".format(moon_age) # where is the moon now moon.compute(now) distance = miles_from_au(moon.earth_distance) phase = moon.phase # where is the Moon one minute later now += ephem.minute moon.compute(now) ps = "⬆" if moon.phase > phase else "⬇" moved = miles_from_au(moon.earth_distance) - distance ds = "⬆" if moved > 0 else "⬇" mph = abs(60 * moved) yield "☽Phase {:.2f}%{}, {:,.1f} miles, {}{:.1f}mph".format( phase, ps, distance, ds, mph)
def timeToNewMoon(self): ''' This function calculates the time to the next new moon. @returns: The time to new moon in decimal hours. ''' next_new_moon = ephem.next_new_moon(self._observer.date) return MoonInfo.DAYS_TO_HOURS * (next_new_moon - self._observer.date)
def moon_phases(start, end, output_format): d = ephem.previous_full_moon(start) d = ephem.previous_full_moon(d) print("Starting from", d) def output_moon_phase(d, phasename, img, attr): if output_format == "sql": print("('%s', 'astronomy', 'naked eye', '%s', '%s', '%s', " "'%s', 240, 240, '%s')," % (phasename + " moon", datestr(d), datestr(d), phasename + " moon", img, attr)) else: print(datestr(d), ":", phasename + " moon") while d <= end: d = ephem.next_first_quarter_moon(d) output_moon_phase( d, "First quarter", 'astronomy/Phase-088.jpg', '<a href=\"http://commons.wikimedia.org/wiki/' 'File:Phase-088.jpg\">Jay Tanner</a>') d = ephem.next_full_moon(d) output_moon_phase( d, "Full", 'astronomy/Phase-180.jpg', '<a href=\"http://commons.wikimedia.org/wiki/' 'File:Phase-180.jpg\">Jay Tanner</a>') d = ephem.next_last_quarter_moon(d) output_moon_phase( d, "Last quarter", 'astronomy/Phase-270.jpg', '<a href=\"http://commons.wikimedia.org/wiki/' 'File:Phase-270.jpg\">Jay Tanner</a>') d = ephem.next_new_moon(d) output_moon_phase( d, "New", 'astronomy/New_Moon.jpg', '<a href="https://commons.wikimedia.org/wiki/' 'File:New_Moon.jpg">QuimGil</a>')
def phase_on_day(date): nnm = ephem.next_new_moon(date) pnm = ephem.previous_new_moon(date) lunation = (date - pnm) / (nnm - pnm) return lunation
def get_moons_in_year(year, month, day): """Returns a list of the full moons, first quarter moons, last quarter moons and new moons in a year.""" moons = [] date = ephem.Date(datetime.date(year, month, day)) while date.datetime().year == year: date = ephem.next_full_moon(date) moons.append((date, 'Luna Llena')) date = ephem.Date(datetime.date(year, month, day)) while date.datetime().year == year: date = ephem.next_first_quarter_moon(date) moons.append((date, 'Cuarto Creciente')) date = ephem.Date(datetime.date(year, month, day)) while date.datetime().year == year: date = ephem.next_last_quarter_moon(date) moons.append((date, 'Cuarto Menguante')) date = ephem.Date(datetime.date(year, month, day)) while date.datetime().year == year: date = ephem.next_new_moon(date) moons.append((date, 'Luna Nueva')) moons_sorted = sorted(moons, key=lambda x: x[0].datetime()) moons_in_year = [] for i in moons_sorted: moons_in_year.append((i[0].datetime().ctime(), i[1])) return moons_in_year
def get_moon_phase(observer): target_date_utc = observer.date target_date_local = ephem.localtime(target_date_utc).date() next_full = ephem.localtime(ephem.next_full_moon(target_date_utc)).date() next_new = ephem.localtime(ephem.next_new_moon(target_date_utc)).date() next_last_quarter = ephem.localtime( ephem.next_last_quarter_moon(target_date_utc)).date() next_first_quarter = ephem.localtime( ephem.next_first_quarter_moon(target_date_utc)).date() previous_full = ephem.localtime( ephem.previous_full_moon(target_date_utc)).date() previous_new = ephem.localtime( ephem.previous_new_moon(target_date_utc)).date() previous_last_quarter = ephem.localtime( ephem.previous_last_quarter_moon(target_date_utc)).date() previous_first_quarter = ephem.localtime( ephem.previous_first_quarter_moon(target_date_utc)).date() if target_date_local in (next_full, previous_full): return 'Full' elif target_date_local in (next_new, previous_new): return 'New' elif target_date_local in (next_first_quarter, previous_first_quarter): return 'First Quarter' elif target_date_local in (next_last_quarter, previous_last_quarter): return 'Last Quarter' elif previous_new < next_first_quarter < next_full < next_last_quarter < next_new: return 'Waxing Crescent' elif previous_first_quarter < next_full < next_last_quarter < next_new < next_first_quarter: return 'Waxing Gibbous' elif previous_full < next_last_quarter < next_new < next_first_quarter < next_full: return 'Waning Gibbous' elif previous_last_quarter < next_new < next_first_quarter < next_full < next_last_quarter: return 'Waning Crescent'
def moons_in_year(year): moons = [] # loop over days in the year: # date = ephem.Date(datetime.date(year, 01, 01)) while date.datetime().year == year: y, m, d, h, min, s = date.tuple() weekday = (date.datetime()).isoweekday() phase = phase_on_day(date) # now determine whether the moon is new of full label = 0 nfm = ephem.next_full_moon(date) nfm = ephem.localtime(nfm) if nfm.day == d and nfm.month == m: label = 1 # full nnm = ephem.next_new_moon(date) nnm = ephem.localtime(nnm) if nnm.day == d and nnm.month == m: label = 2 # new moons.append((y, m, d, phase, label, weekday)) date = ephem.date(date + 1.0) return moons
def checkMoonPhaseDirection(date): new_moon = ephem.next_new_moon(date) full_moon = ephem.next_full_moon(date) if new_moon < full_moon: return 'Waning ' else: return 'Waxing '
def getMoonPhases(): date = ephem.now() new_moon = str(ephem.next_new_moon(date)) first_quarter_moon = str(ephem.next_first_quarter_moon(date)) full_moon = str(ephem.next_full_moon(date)) last_quarter_moon = str(ephem.next_last_quarter_moon(date)) return new_moon, first_quarter_moon, full_moon, last_quarter_moon
def getEphem(): global next_sunrise global next_sunset global lnext_sunrise global lnext_sunset global next_full_moon global next_new_moon o = ephem.Observer() o.lat = lat o.long = long s = ephem.Sun() s.compute() print o date_sunrise = str(ephem.localtime(o.next_rising(s))) # Next sunrise date_sunset = str(ephem.localtime(o.next_setting(s))) # Next sunset next_sunrise = date_sunrise.split(" ", 1)[1].split(".", 1)[0] next_sunset = date_sunset.split(" ", 1)[1].split(".", 1)[0] lnext_sunrise = float(next_sunrise.replace(":", "")) lnext_sunset = float(next_sunset.replace(":", "")) print next_sunrise print next_sunset date_full_moon = str(ephem.next_full_moon(o.date)) date_new_moon = str(ephem.next_new_moon(o.date)) aux = date_full_moon.split(" ", 1)[0] next_full_moon = aux.split("/", 2)[2] # + "/" + aux.split("/",2)[1] + "/" + aux.split("/",1)[0] # If you want to see entire date next_full_moon += getMonthName(aux.split("/", 2)[1]) aux = date_new_moon.split(" ", 1)[0] next_new_moon = aux.split("/", 2)[2] # + "/" + aux.split("/",2)[1] + "/" + aux.split("/",1)[0] # If you want to see entire date next_new_moon += getMonthName(aux.split("/", 2)[1]) print next_new_moon print next_full_moon
def visibility(ra, dec, observatory, time): source = SkyCoord(ra=Angle(ra * u.deg), dec=(dec * u.deg)) location = observatory.position time = Time(time) altaz = source.transform_to(AltAz(obstime=time, location=location)) altaz_sun = get_sun(time).transform_to( AltAz(obstime=time, location=location)) altaz_moon = get_moon(time).transform_to( AltAz(obstime=time, location=location)) delta_time = np.linspace(0, 24, 200) * u.hour frame = AltAz(obstime=time + delta_time, location=location) frame_night = source.transform_to(frame) frame_sun_night = get_sun(time + delta_time).transform_to(frame) frame_moon_night = get_moon(time + delta_time).transform_to(frame) moon_distance = np.mean( source.separation( SkyCoord( get_moon(time + delta_time).ra, get_moon(time + delta_time).dec))) sun_distance = np.mean( source.separation( SkyCoord( get_sun(time + delta_time).ra, get_sun(time + delta_time).dec))) date = ephem.Date(time.value) moon_phase = (date - ephem.previous_new_moon(date)) / ( ephem.next_new_moon(date) - ephem.previous_new_moon(date)) return altaz, delta_time, frame_night, frame_sun_night, moon_distance, sun_distance, moon_phase
def _check_trigger_special(self, date_tuple, utc_offset=0): """ Returns boolean indicating if the trigger is active at the given time. The date tuple should be in the local time. """ cpm = False if self.string_tab == '@fullmoon': cpm = ephem.next_full_moon(date_tuple) elif self.string_tab == '@newmoon': cpm = ephem.next_new_moon(date_tuple) elif self.string_tab == '@firstquarter': cpm = ephem.next_first_quarter_moon(date_tuple) elif self.string_tab == '@lastquarter': cpm = ephem.next_last_quarter_moon(date_tuple) elif self.string_tab == '@equinox': cpm = ephem.next_equinox(date_tuple) elif self.string_tab == '@solstice': cpm = ephem.next_solistice(date_tuple) elif self.string_tab in ['@dawn', '@dusk']: bobs = ephem.Sun() if self.string_tab == '@dawn': cpm = self._city.next_rising(bobs) else: cpm = self._city.next_setting(bobs) if cpm: """ Do compare """ print cpm return True else: return False
def LunarCalendar(nian, type=1): # type=1时截止到次年冬至朔,=0时截止到次年冬至朔次月 dzs = findDZS(nian) shuo = dzs # 计算用朔,date格式 shuoJD = [ephem.julian_date(dzs)] # 存储ut+8 JD,起冬至朔 next_dzsJD = ephem.julian_date(findDZS(nian + 1)) # 次年冬至朔 i = -1 # 中气序,从0起计 j = -1 # 计算连续两个冬至月中的合朔次数,从0起计 zry = 0 flag = False # 查找所在月及判断置闰 while not DateCompare(shuoJD[j + type], next_dzsJD): # 从冬至月起查找,截止到次年冬至朔 i += 1 j += 1 shuo = ephem.next_new_moon(shuo) # 次月朔 shuoJD.append(ephem.julian_date(shuo)) # 查找本月中气,若无则置闰 if j == 0: continue # 冬至月一定含中气,从次月开始查找 angle = (-90 + 30 * i) % 360 # 本月应含中气,起冬至 qJD = SolarTerms(nian, angle) # 不判断气在上月而后气在后月的情况,该月起的合朔次数不超过气数,可省去 if DateCompare(qJD, shuoJD[j + 1]) and flag == False: # 中气在次月,则本月无中气 zry = j + 1 # 置闰月 i -= 1 flag = True # 仅第一个无中气月置闰 # 生成农历月序表 ymb = [] for k in range(len(shuoJD)): ymb.append(yuefen[(k - 2) % 12]) # 默认月序 if j + type == 13: # 仅12次合朔不闰,有闰时修改月名 if k + 1 == zry: ymb[k] = '闰' + yuefen[(k - 1 - 2) % 12] elif k + 1 > zry: ymb[k] = yuefen[(k - 1 - 2) % 12] return ymb, shuoJD # 月名表,合朔JD日期表
def get_phase_on_day(): """Returns a symbolic value and name for the current moon phase""" date=ephem.Date(datetime.datetime.now()) nnm = ephem.next_new_moon (date) pnm = ephem.previous_new_moon(date) lunation=(date-pnm)/(nnm-pnm) if lunation >= 0 and lunation <= 0.125: return "🌚 new" elif lunation >= 0.126 and lunation <= 0.25: return "🌒 waxing crescent" elif lunation >= 0.26 and lunation <= 0.375: return "🌓 first quarter" elif lunation >= 0.376 and lunation <= 0.5: return "🌔 waxing gibbous" elif lunation >= 0.51 and lunation <= 0.625: return lunation return "� full" elif lunation >= 0.626 and lunation <= 0.75: return "🌖 waning gibbous" elif lunation >= 0.76 and lunation <= 0.875: return "🌗 last quarter" elif lunation >= 0.876 and lunation <= 1.0: return "🌘 waning crescent"
def __init__(self): self.__logger = logging.getLogger(self.__class__.__name__) #find current moon phase now = ephem.now() new_date = ephem.next_new_moon(now) first_quarter_date = ephem.next_first_quarter_moon(now) full_date = ephem.next_full_moon(now) last_quarter_date = ephem.next_last_quarter_moon(now) delta = float('inf') if new_date - now < delta: delta = new_date - now self.__current_phase = MoonUpdater.LAST_QUARTER_MOON self.__current_phase_date = ephem.previous_last_quarter_moon( now).datetime() if first_quarter_date - now < delta: delta = first_quarter_date - now self.__current_phase = MoonUpdater.NEW_MOON self.__current_phase_date = ephem.previous_new_moon(now).datetime() if full_date - now < delta: delta = full_date - now self.__current_phase = MoonUpdater.FIRST_QUARTER_MOON self.__current_phase_date = ephem.previous_first_quarter_moon( now).datetime() if last_quarter_date - now < delta: delta = last_quarter_date - now self.__current_phase = MoonUpdater.FULL_MOON self.__current_phase_date = ephem.previous_full_moon( now).datetime()
def get_next_date_special(self, date_tuple, utc_offset=0): """ Returns next ephemeris date the given time. The date tuple should be in the local time. return date tupple """ cpm = None if self.string_tab == '@fullmoon': cpm = ephem.next_full_moon(date_tuple) elif self.string_tab == '@newmoon': cpm = ephem.next_new_moon(date_tuple) elif self.string_tab == '@firstquarter': cpm = ephem.next_first_quarter_moon(date_tuple) elif self.string_tab == '@lastquarter': cpm = ephem.next_last_quarter_moon(date_tuple) elif self.string_tab == '@equinox': cpm = ephem.next_equinox(date_tuple) elif self.string_tab == '@solstice': cpm = ephem.next_solstice(date_tuple) elif self.string_tab in ['@dawn', '@dusk']: bobs = ephem.Sun() date = "{0}/{1}/{2}".format(date_tuple[0], date_tuple[1], date_tuple[2]) if self.string_tab == '@dawn': cpm = self._city.next_rising(bobs, start=date) else: cpm = self._city.next_setting(bobs, start=date) if cpm: return cpm.tuple()[:-1] return None
def get_phase_on_day(year, month, day): date = ephem.Date(datetime.date(year, month, day)) nnm = ephem.next_new_moon(date) pnm = ephem.previous_new_moon(date) lunation = (date - pnm) / (nnm - pnm) return lunation
def events_until(limit): initial_date = ephem.Date(datetime.now()) events = {} now = initial_date while ephem.localtime(now) <= limit: now = ephem.next_full_moon(now) events[now] = "🌕" now = initial_date while ephem.localtime(now) <= limit: now = ephem.next_new_moon(now) events[now] = "🌑" now = initial_date while ephem.localtime(now) <= limit: now = ephem.next_vernal_equinox(now) events[now] = "spring equinox" now = initial_date while ephem.localtime(now) <= limit: now = ephem.next_autumnal_equinox(now) events[now] = "fall equinox" now = initial_date while ephem.localtime(now) <= limit: now = ephem.next_winter_solstice(now) events[now] = "winter solstice" now = initial_date while ephem.localtime(now) <= limit: now = ephem.next_summer_solstice(now) events[now] = "summer solstice" return events
def _check_trigger_special(self, date_tuple, utc_offset=0): """ Returns boolean indicating if the trigger is active at the given time. The date tuple should be in the local time. """ cpm = False; if self.string_tab == '@fullmoon': cpm = ephem.next_full_moon(date_tuple) elif self.string_tab == '@newmoon': cpm = ephem.next_new_moon(date_tuple) elif self.string_tab == '@firstquarter': cpm = ephem.next_first_quarter_moon(date_tuple) elif self.string_tab == '@lastquarter': cpm = ephem.next_last_quarter_moon(date_tuple) elif self.string_tab == '@equinox': cpm = ephem.next_equinox(date_tuple) elif self.string_tab == '@solstice': cpm = ephem.next_solistice(date_tuple) elif self.string_tab in ['@dawn', '@dusk']: bobs = ephem.Sun() if self.string_tab == '@dawn': cpm = self._city.next_rising(bobs) else: cpm = self._city.next_setting(bobs) if cpm: """ Do compare """ print cpm return True else: return False
def dzs_search(year): # 寻找年前冬至月朔日 if year == 1: year -= 1 # 公元0改为公元前1 dz = ephem.next_solstice((year - 1, 12)) # 年前冬至 jd = ephem.julian_date(dz) # 可能的三种朔日 date1 = ephem.next_new_moon(ephem.Date(jd - 2415020 - 0)) jd1 = ephem.julian_date(date1) date2 = ephem.next_new_moon(ephem.Date(jd - 2415020 - 29)) jd2 = ephem.julian_date(date2) date3 = ephem.next_new_moon(ephem.Date(jd - 2415020 - 31)) jd3 = ephem.julian_date(date3) if DateCompare(jd, jd1): # 冬至合朔在同一日或下月 return date1 elif DateCompare(jd, jd2) and (not DateCompare(jd, jd1)): return date2 elif DateCompare(jd, jd3): # 冬至在上月 return date3
def findDZS(year): # 寻找年前冬至月朔日 if year == 1: year -= 1 # 公元元年前冬至在公元前1年 dz = ephem.next_solstice((year - 1, 12)) # 年前冬至 jd = ephem.julian_date(dz) # 可能的三种朔日 date1 = ephem.next_new_moon(JD2date(jd - 0)) jd1 = ephem.julian_date(date1) date2 = ephem.next_new_moon(JD2date(jd - 29)) jd2 = ephem.julian_date(date2) date3 = ephem.next_new_moon(JD2date(jd - 31)) jd3 = ephem.julian_date(date3) if DateCompare(jd, jd1): # 冬至合朔在同一日或下月 return date1 elif DateCompare(jd, jd2) and (not DateCompare(jd, jd1)): return date2 elif DateCompare(jd, jd3): # 冬至在上月 return date3
def moonphase(self, MJD): ephemdate = ephem.Date((Time(MJD, format = 'mjd', scale = 'utc').isot).replace("T", " ")) ephemnextnewmoon = ephem.next_new_moon(ephemdate) ephempreviousnewmoon = ephem.previous_new_moon(ephemdate) moonphase = min(ephemnextnewmoon - ephemdate, ephemdate - ephempreviousnewmoon) return moonphase
def Solar2LunarCalendar(date): # 默认输入ut+8时间 JD = ephem.julian_date(date) - 8 / 24 # ut year = ephem.Date(JD + 8 / 24 - 2415020).triple()[0] shuo = [] # 存储date shuoJD = [] # 存储JD # 判断所在年 shuo.append(dzs_search(year)) # 本年冬至朔 next_dzs = dzs_search(year + 1) # 次年冬至朔 this_dzsJD = ephem.julian_date(shuo[0]) next_dzsJD = ephem.julian_date(next_dzs) nian = year # 农历年 if DateCompare(JD, next_dzsJD): # 该日在次年 shuo[0] = next_dzs # 次年冬至朔变为本年 next_dzs = dzs_search(year + 2) nian += 1 if not DateCompare(JD, this_dzsJD): # 该日在上年 next_dzs = shuo[0] # 本年冬至朔变为次年 shuo[0] = dzs_search(year - 1) nian -= 1 next_dzsJD = ephem.julian_date(next_dzs) shuoJD.append(ephem.julian_date(shuo[0])) # 找到的年前冬至朔 # 查找所在月及判断置闰 szy = 0 i = -1 # 中气序 j = -1 # 计算连续两个冬至月中的合朔次数 zry = 99 # 无效值 flag = False while not DateCompare(shuoJD[j], next_dzsJD): # 从冬至月起查找,截止到次年冬至朔 i += 1 j += 1 # 查找所在月,起冬至朔 if DateCompare(JD, shuoJD[j]): szy += 1 # date所在月 newmoon = shuoJD[j] shuo.append(ephem.next_new_moon(shuo[j])) # 次月朔 shuoJD.append(ephem.julian_date(shuo[j + 1])) # 查找本月中气,若无则置闰 if j == 0: continue # 冬至月一定含中气,从次月开始查找 angle = (-90 + 30 * i) % 360 # 本月应含中气,起冬至 qJD = SolarTerms(nian, angle) # 不判断气在上月而后气在后月的情况,该月起的合朔次数不超过气数,可省去 if DateCompare(qJD, shuoJD[j + 1]) and flag == False: # 中气在次月,则本月无中气 zry = j + 1 # 置闰月 i -= 1 flag = True # 仅第一个无中气月置闰 # 判断置闰 if j == 12 and zry != 99: # 有无中气月但合朔仅12次 zry = 99 if szy >= zry % 12 and zry != 99: szy -= 1 # 置闰后的月序名 # 以正月开始的年干支 if szy < 3: nian -= 1 # 正月前属上年 if nian < 0: nian += 1 rq = math.floor(JD + 8 / 24 + 0.5) - math.floor(newmoon + 8 / 24 + 0.5) # 日干支 # return date + ' 为农历:' + yuefen[(szy - 3) % 12] + nlrq[rq] + '\n' return "%02d-%02d" % ((szy - 3) % 12 + 1, rq + 1), str(yuefen[(szy - 3) % 12] + nlrq[rq])
def fractional_age(self): """The moon's fractional age. Always less than 1.0. Returns ------- float """ prev_new = ephem.previous_new_moon(self.observer.date) next_new = ephem.next_new_moon(self.observer.date) return (self.observer.date - prev_new) / (next_new - prev_new)
def __init__(self, moonphase, date): self.info_pass = "" if moonphase == "full": self.moon = ephem.next_full_moon(date) elif moonphase == "new": self.moon = ephem.next_new_moon(date) elif moonphase == "first_quarter": self.moon = ephem.next_first_quarter_moon(date) elif moonphase == "last_quarter": self.moon = ephem.next_last_quarter_moon(date)
def new_moons_in_year(year): "Returns a list of New Moons in the specified year" date = ephem.Date(str(year)) new_moons = [] while True: date = ephem.next_new_moon(date) if date.triple()[0] > year: break new_moons.append(date) return new_moons
def fullmoon(bot, update): message = update.message.text if message.endswith('?'): replaces = message.replace('?', '').replace('-', '/') separator = replaces.split() next_date = ephem.next_new_moon(separator[-1]) convert_type = next_date.datetime() times = datetime.datetime.strftime(convert_type, '%Y-%m-%d %H:%M:%S') update.message.reply_text('Ближайшее полнолуние: ' + times) else: update.message.reply_text('Вы забыли поставить знак "?"')
def time_to_new_moon(self): """The time (hours) to the next new moon. This function calculates the time to the next new moon. Returns ------- float """ next_new_moon = ephem.next_new_moon(self.observer.date) return MoonInfo.DAYS_TO_HOURS * (next_new_moon - self.observer.date)
def get_phase_on_day(year, month, day): """Returns a floating-point number from 0-1. where 0=new, 0.25 = first_quarter, 0.5=full, 0.75 = last_quarter, 1=new""" date = ephem.Date(datetime.date(year, month, day)) nnm = ephem.next_new_moon(date) pnm = ephem.previous_new_moon(date) lunation = (date - pnm) / (nnm - pnm) return lunation
def lunar_start(year, month, day): # 🌑 🌒 🌓 🌔 🌕 🌖 🌗 🌘 🌑 # >>> ephem.next_full_moon((2013, 11, 17)).tuple()[:3] # (2013, 11, 17) if (year, month, day) == ephem.next_full_moon((year, month, day)).tuple()[:3]: return u"🌕" elif (year, month, day) == ephem.next_first_quarter_moon((year, month, day)).tuple()[:3]: return u"🌓" elif (year, month, day) == ephem.next_last_quarter_moon((year, month, day)).tuple()[:3]: return u"🌗" elif (year, month, day) == ephem.next_new_moon((year, month, day)).tuple()[:3]: return u"🌑"
def getMoonPhase( n ): if not isinstance( n, RPNDateTime ): raise ValueError( '\'moon_phase\' expects a date-time argument' ) datetime = n.to( 'utc' ).format( ) previous = RPNDateTime.convertFromEphemDate( ephem.previous_new_moon( datetime ) ).getLocalTime( ) next = RPNDateTime.convertFromEphemDate( ephem.next_new_moon( datetime ) ).getLocalTime( ) cycle = next - previous current = n - previous return current.total_seconds( ) / cycle.total_seconds( )
def findNextFourPhases(self): ''' This function returns a sorted tuple of the next four phases with the key being the short name for the phase. The value is a modified Julian date for the phase. @return: A list of tuples sorted by the value date. ''' phases = {} phases["new"] = ephem.next_new_moon(self._observer.date) phases["fq"] = ephem.next_first_quarter_moon(self._observer.date) phases["full"] = ephem.next_full_moon(self._observer.date) phases["tq"] = ephem.next_last_quarter_moon(self._observer.date) return sorted(phases.items(), key=lambda x:x[1])
def moon_is(adate): " Find the next moon shape, returns FM .. NM." # TODO(mohsin) This is expensive, should cache it for whole month. # ephem.previous_new_moon(date) # ephem.previous_first_quarter_moon(date) # ephem.previous_full_moon(date) # ephem.previous_last_quarter_moon(date) date = ephem.Date(adate) if cmp_ymd(ephem.next_new_moon(date) , date): return 'NM' if cmp_ymd(ephem.next_first_quarter_moon(date), date): return 'FQ' if cmp_ymd(ephem.next_full_moon(date) , date): return 'FM' if cmp_ymd(ephem.next_last_quarter_moon(date) , date): return 'LQ' return ''
def moon_age(self, timestamp): """Return the age of the moon at the given time.""" d1 = pyEphem.next_new_moon(timestamp).datetime() d2 = pyEphem.previous_new_moon(timestamp).datetime() # Check format of provided time. If it wasn't a timestamp, make it one. if isinstance(timestamp, datetime.datetime) is False: timestamp = timestamp.datetime() # Find the total time since new moon and then convert to days if (d1 - timestamp) < (timestamp - d2): return (timestamp - d1).total_seconds() / 3600. / 24. else: return (timestamp - d2).total_seconds() / 3600. / 24.
def getMoonPhase( n ): '''Returns the current moon phase as a percentage, starting from the new moon.''' if not isinstance( n, RPNDateTime ): raise ValueError( '\'moon_phase\' expects a date-time argument' ) datetime = n.format( ) previous = RPNDateTime.convertFromEphemDate( ephem.previous_new_moon( datetime ) ) next = RPNDateTime.convertFromEphemDate( ephem.next_new_moon( datetime ) ) cycle = next - previous current = n - previous return current.total_seconds( ) / cycle.total_seconds( )
def moon(): m = ephem.Moon() m.compute(datetime.utcnow()) phase = m.moon_phase colong = m.colong nnm = ephem.next_new_moon(datetime.utcnow()) nfm = ephem.next_full_moon(datetime.utcnow()) result = {'next_new_moon': str(nnm), 'next_full_moon': str(nfm), 'visibility': str(phase), 'colong': str(colong)} return result
def __init__(self, year, timezone='Europe/Copenhagen', outformat='text'): """Compute moon phases for a whole year""" # Backtrack and look ahead to be sure to catch moons around newyear start_date = ephem.Date((year-1, 9, 1)) end_date = ephem.Date((year+1, 3, 1)) self.moon_phases = {} new_moon = ephem.next_new_moon(start_date) first_quarter = ephem.next_first_quarter_moon(start_date) full_moon = ephem.next_full_moon(start_date) last_quarter = ephem.next_last_quarter_moon(start_date) while True: local_new_moon = utc2localtime(new_moon.datetime()) local_first_quarter = utc2localtime(first_quarter.datetime()) local_full_moon = utc2localtime(full_moon.datetime()) local_last_quarter = utc2localtime(last_quarter.datetime()) if local_new_moon.year == year: self.moon_phases[local_new_moon] = \ self.moon_phase_names('new_moon', outformat) if local_first_quarter.year == year: self.moon_phases[local_first_quarter] = \ self.moon_phase_names('first_quarter', outformat) if local_full_moon.year == year: self.moon_phases[local_full_moon] = \ self.moon_phase_names('full_moon', outformat) if local_last_quarter.year == year: self.moon_phases[local_last_quarter] = \ self.moon_phase_names('last_quarter', outformat) new_moon = ephem.next_new_moon(new_moon) first_quarter = ephem.next_first_quarter_moon(first_quarter) full_moon = ephem.next_full_moon(full_moon) last_quarter = ephem.next_last_quarter_moon(last_quarter) if (new_moon > end_date) and (first_quarter > end_date) and \ (full_moon > end_date) and (last_quarter > end_date): break
def get_moon_year(date,ignoreTime = True ): pve = ephem.previous_vernal_equinox(date) nve = ephem.next_vernal_equinox(pve) fnm = pnm = ephem.next_new_moon(math.floor(pve)) # check if date is still in previous lunar year if date < fnm: nve = pve pve = ephem.previous_vernal_equinox(nve) fnm = pnm = ephem.next_new_moon(math.floor(pve)) #print str(date) + " : " + str(pve) + " : " + str(nve) nm = pve moonyear = [] while nm < nve: nm = ephem.next_new_moon(pnm) if ignoreTime: moonyear += [ math.floor(nm)-math.floor(pnm) ] else: moonyear += [ round(nm-pnm) ] pnm = nm return (moonyear,fnm,nm)
def getMoonIllumination(self,dt): """ Input datetime object (in UTC), and uses ephem and interpolation to get fraction of moon illuminated. Returns float in [0,1] Usually absolute accuracy 10%, sometimes up to 20% """ dtEphem = ephem.Date(dt) nextFull = ephem.next_full_moon(dt) followingNew = ephem.next_new_moon(nextFull) period = 2.*(followingNew-nextFull) #print "dtEphem: {:f}".format(dtEphem) #print "nextFull: {:f}".format(nextFull) #print "followingNew: {:f}".format(followingNew) #print "period {:f}".format(period) return 0.5*numpy.cos(2*numpy.pi*(dtEphem-nextFull)/period)+0.5
def get_moons_in_year(year): """Returns a list of the full and new moons in a year. The list contains tuples of either the form (DATE,'full') or the form (DATE,'new')""" moons=[] date=ephem.Date(datetime.date(year,1,1)) while date.datetime().year==year: date=ephem.next_new_moon(date) moons.append( (date,'new') ) #Note that previous_first_quarter_moon() and previous_last_quarter_moon() #are also methods moons.sort(key=lambda x: x[0]) return moons
def _get_phase_on_day(self, date = datetime.date.today()): '''Returns a floating-point number from 0-1. where 0=new, 0.5=full, 1=new''' #Ephem stores its date numbers as floating points, which the following uses #to conveniently extract the percent time between one new moon and the next #This corresponds (somewhat roughly) to the phase of the moon. #Use Year, Month, Day as arguments date=ephem.Date(date) nnm = ephem.next_new_moon (date) pnm = ephem.previous_new_moon(date) lunation=(date-pnm)/(nnm-pnm) #Note that there is a ephem.Moon().phase() command, but this returns the #percentage of the moon which is illuminated. This is not really what we want. return lunation
def get_current_moon_phase(): """ Get the current moon phase """ # get the dates of the last and next new moon moon_observer.date = datetime.now() phase_end = ephem.next_new_moon(moon_observer.date) phase_start = ephem.previous_new_moon(moon_observer.date) # based on that figure out what part of the phase we are in. Phase goes from [0,1) phase = (moon_observer.date - phase_start) / (phase_end - phase_start) # 8 moon phases, so do this for easy indexing phase *= 8 # round to the nearest phase and wrap aroudn for the 7.5-7.9 range mapping to 0 phase = round(phase) % 8 return "The current moon phase is {0}".format(moon_phases[int(phase)])
def calculate_moon_phase(self): m = ephem.Moon() m.compute(self.observer) nnm = ephem.next_new_moon(self.observer.date) pnm = ephem.previous_new_moon(self.observer.date) # for use w. moon_phases.ttf A -> just past newmoon, # Z just before newmoon # '0' is full, '1' is new # note that we cannot use m.phase as this is the percentage of the moon # that is illuminated which is not the same as the phase! lunation = (self.observer.date - pnm) / (nnm - pnm) symbol = lunation * 26 # print("Lunation as a 1/26 is: %f" % symbol) if symbol < 0.5 or symbol > 25.5: symbol = '*' # new moon else: symbol = chr(ord('A') + int(symbol + 0.5) - 1) return symbol
def process(): data = request.get_json(silent=False) app.logger.info("Handling request with text: " + data['text']) if "new moon" in data['text']: d = ephem.next_new_moon(time.strftime("%Y/%m/%d")) print(time.strftime("%Y/%m/%d")) strResponse = 'The next new moon is ' + str(d) elif "full moon" in data['text']: d = ephem.next_full_moon(time.strftime("%Y/%m/%d")) strResponse = 'The next full moon is ' + str(d) else: strResponse = 'I am sorry, I don\'t understand your question' \ ' regarding moons.' response = AgentResponse(text=strResponse) return json.dumps(response.export())
def get_lunation_day(today, number_of_phase_ids=28): '''Given a date (of type ephem.Date), return a lunar cycle day ID number (integer in [0:(number_of_phase_ids - 1)]), corresponding to the lunation for the given date. 0 = new moon. Arguments: today (ephem.date): the date for which to get the lunation day number Optional: number_of_phase_ids (integer, default = 28): the number of unique lunar cycle day identifiers, e.g. the number of moon phase icons available to display the lunation each day. Returns: integer in range(0, number_of_phase_ids - 1), today's lunation phase ID number. The lunation day is calibrated to the quarter phases calculated by pyephem, but it does not always agree exactly with percent illumination, which is a different calculation entirely.''' last_new = ephem.previous_new_moon(today) next_new = ephem.next_new_moon(today) num = number_of_phase_ids - 1 first_approx = round((today - last_new) / (next_new - last_new) * num) if first_approx < np.ceil(num / 4): next_fq = ephem.next_first_quarter_moon(last_new) if today < next_fq: return round((today - last_new) / (next_fq - last_new) * (num / 4)) if first_approx < np.ceil(num / 2): next_full = ephem.next_full_moon(last_new) if today < next_full: return round((today - last_new) / (next_full - last_new) * (num / 2)) if first_approx < np.ceil(num * 3 / 4): next_lq = ephem.next_last_quarter_moon(last_new) if today < next_lq: return round((today - last_new) / (next_lq - last_new) * (num * 3 / 4)) return first_approx
def main(observer): date = ephem.now() moon = ephem.Moon(date) # Young or old Moon (within 72 hours of new) previous_new = ephem.previous_new_moon(date) age = 24 * (date - previous_new) if age <= 72: print("Young Moon: {:.1f} hours".format(age)) else: next_new = ephem.next_new_moon(date) age = 24 * (next_new - date) if age <= 72: print("Old Moon: {:.1f} hours".format(age)) print("Phase {0.moon_phase:.2%}".format(moon)) distance = miles_from_au(moon.earth_distance) moon.compute(ephem.Date(date + ephem.hour)) moved = miles_from_au(moon.earth_distance) - distance print( 'Earth distance: {:13,.0f} miles, {:+5.0f} mph'.format( distance, moved)) observer.date = date moon.compute(observer) m2 = moon.copy() distance = miles_from_au(moon.earth_distance) observer.date = ephem.Date(date + ephem.hour) moon.compute(observer) moved = miles_from_au(moon.earth_distance) - distance print( 'Observer distance: {:13,.0f} miles, {:+5.0f} mph'.format( distance, moved)) print("Azimuth {}".format(_(m2.az))) print("Altitude {}".format(_(m2.alt))) print("Declination {}".format(_(m2.dec))) print("\n") for event in moon_phase_events(): print(str(event))
def sf_sun_moon(date): sf = ep.Observer() #sf.pressure = 0 #sf.horizon = '-0:34' sf.lat, sf.lon = '37.46', '-122.26' sf.date = date + ' 20:00' # noon PST sun_rise = (sf.previous_rising(ep.Sun())) sun_set = (sf.next_setting(ep.Sun())) sf.date = date + ' 09:00' # 1am PST moon_rise = (sf.previous_rising(ep.Moon())) # print 'mrise', moon_rise moon_set = (sf.next_setting(ep.Moon())) # print 'mset', moon_set sun = ep.localtime(sun_set) - ep.localtime(sun_rise) sun_min = sun.total_seconds() / 60 moon = ep.localtime(moon_set) - ep.localtime(moon_rise) # print 'moon', moon moon_min = moon.total_seconds() / 60 # print 'moonmin', moon_min nnm = ep.next_new_moon(date) pnm = ep.previous_new_moon(nnm) lunation=(sf.date-pnm)/(nnm-pnm) return sun_min, lunation
def next_ve_nm( date, accuracy = 1, dow = None ): "get next vernal equinox when the same as a new moon when on a wednesday" if type(date) is enoch.Date: e = date else: e = enoch.Date ( date ) ve = e.djd nm = 0 found = False while not found: ve = ephem.next_vernal_equinox ( ve ) nm = ephem.next_new_moon ( math.floor(ve)) df = math.fabs(ve-nm) if df < accuracy: e.set ( nm ) if dow is not None: if e.dayofweek == dow: found = True else: found = True return {"ve":ve,"enoch":e}