Esempio n. 1
0
def astro_moonnextfull(DATETIME=None):

    if DATETIME == None:
        eventdate = ephem.localtime(ephem.next_full_moon(ephem.now()))
        return "FM: " + eventdate.strftime('%b %d %H:%M')
    else:
        return ephem.next_full_moon(DATETIME)
Esempio n. 2
0
def next_full_moon(update, context):
    command_text = update.message.text.split()
    if len(command_text) < 2:
        update.message.reply_text(
            ephem.next_full_moon(time.strftime('%Y/%m/%d')))
    else:
        update.message.reply_text(ephem.next_full_moon(command_text[1]))
Esempio n. 3
0
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 ''
Esempio n. 4
0
def get_next_full_moon(bot, update, args):
    """Показывает дату ближайшего полнолуния"""
    input_date = ' '.join(args)

    if update.message.text == '/next_full_moon':
        full_moon_date = ephem.next_full_moon(datetime.now())
        update.message.reply_text('Ближайшее полнолуние будет: {}'.format(
            datetime.strptime(str(full_moon_date),
                              '%Y/%m/%d %X').strftime('%d %b %Y'), ))
    elif update.message.text == '/next_full_moon help':
        update.message.reply_text("""
            Справка по команде next_full_moon:

            вызов /next_full_moon - покажу ближайшее полнолуние
            вызов /next_full_moon <дата> - покажу ближайшее полнолуние от заданной даты.

            Формат даты для ввода: 2019-01-01 (год, месяц, число)
            """)

    elif input_date:
        try:
            input_date = datetime.strptime(input_date, '%Y-%m-%d')
        except ValueError:
            update.message.reply_text(
                'Ты написал дату не так!\nНапиши в таком виде: 2019-01-01 (год-месяц-день)',
            )
        full_moon_date = ephem.next_full_moon(input_date)
        update.message.reply_text('Полнолуние будет: {}'.format(
            datetime.strptime(str(full_moon_date),
                              '%Y/%m/%d %X').strftime('%d %b %Y'), ))
Esempio n. 5
0
    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
Esempio n. 6
0
def next_full_moon(str):
    date = re.findall(r'\d{4}/\d{2}/\d{2}', str)
    if date != []:
        result = 'Ближайшее полнолуние: %s' % ephem.next_full_moon(date[0])
    elif re.findall(r'\d', str) != []:
        result = 'Укажите дату в формате ГГГГ/ММ/ДД'
    else:
        result = 'Ближайшее полнолуние: %s' % ephem.next_full_moon(datetime.now())
    return result
Esempio n. 7
0
def next_full_moon(bot, update, args):
    if args == []:
        curr_date = datetime.datetime.now()
        print(type(curr_date))
        text = ephem.next_full_moon(curr_date)
    else:
        try:
            args = args[0] + ' 08:00:00'
            text = ephem.next_full_moon(args)
        except:
            print('Неизвестный формат даты, укажите гггг/мм/дд')
    update.message.reply_text(text)
Esempio n. 8
0
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])
Esempio n. 9
0
def next_full_moon(update, context):
    text_message = get_user_message(update.message.text, 15)
    user_date = datetime.strptime(text_message, '%Y/%m/%d')
    full_moon_date = str(ephem.next_full_moon(user_date))
    next_full_moon = ephem.next_full_moon(user_date)
    date_next_full_moon = datetime.strptime(str(next_full_moon),
                                            '%Y/%m/%d %H:%M:%S')
    if date_next_full_moon > datetime.now():
        update.message.reply_text(
            f'Ближайшее полнолуние после {user_date.strftime("%d.%m.%Y")} будет {date_next_full_moon.strftime("%d.%m.%Y")}.'
        )
    else:
        update.message.reply_text(
            f'Ближайшее полнолуние после {user_date.strftime("%d.%m.%Y")} было {date_next_full_moon.strftime("%d.%m.%Y")}.'
        )
Esempio n. 10
0
    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
Esempio n. 11
0
 def full_moon_getdate(user_date):
     """По полученой на вход дате получаем дату полнолуния"""
     try:
         full_moon_date = ephem.next_full_moon(user_date)
         return full_moon_date
     except AttributeError:
         return f'Пока не уверен в данном исключении.'
Esempio n. 12
0
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 write_full_moons(start_date=first_year,
                     end_date=that_night,
                     file_path=moon_file_path,
                     printbool=False,
                     over_write=True):
    if over_write: clear_file(file_path)
    moon_file = open(file_path, "a")
    #if observer is None:
    #    observer = create_hogwarts_observer()
    moon = ephem.Moon()

    current_date = start_date
    i = 0
    while (current_date < end_date):
        if printbool:
            print(i, ": ", current_date)
            i = i + 1
        moon_ed = ephem.next_full_moon(current_date)
        moon_dt = moon_ed.datetime()
        moon_s = ""
        if is_new_school_year(moon_dt):
            moon_s = get_marauders_school_year_string(moon_dt,
                                                      printbool=printbool)
        moon_s = moon_s + dt_pretty_print(moon_dt, printbool=printbool)
        moon_file.write(moon_s)

        current_date = moon_dt
    #end while

    moon_file.close()
    return
Esempio n. 14
0
 def timeToFullMoon(self):
     '''
     This function calculates the time to the next full moon.
     @returns: The time to full moon in decimal days.
     '''
     next_full_moon = ephem.next_full_moon(self._observer.date)
     return next_full_moon - self._observer.date
Esempio n. 15
0
 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()
Esempio n. 16
0
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
Esempio n. 17
0
    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
Esempio n. 18
0
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 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'
Esempio n. 20
0
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>')
Esempio n. 21
0
def handle_text(bot, update):

    text = update.message.text.lower()

    command = "когда ближайшее полнолуние после"

    my_date = ""
    if text[0:len(command)] == command:
        my_date = text[len(command) + 1:]
        try:
            update.message.reply_text(str(ephem.next_full_moon(my_date)))
        except ValueError:
            update.message.reply_text("Какая-то странная дата: " + my_date)

    # playing cities game
    input_city = update.message.text
    print("количество городов " + str(len(cities)))
    if input_city in cities:
        # This is our city
        last_letter = input_city[-1]
        for city in cities:
            if city[:1].lower() == last_letter:
                update.message.reply_text(city + ", ваш ход")
                cities.remove(input_city)
                cities.remove(city)
                return
Esempio n. 22
0
def full_moon(bot, update):
    user_date = update.message.text.split(" ")[1]
    try:
        answer = ephem.next_full_moon(user_date)
        update.message.reply_text(answer)
    except ValueError:
        update.message.reply_text("Даты выглядят так 'год-месяц-день'")
Esempio n. 23
0
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
Esempio n. 24
0
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
Esempio n. 25
0
def next_f_moon(question):
    q = question
    q = q[33:-1]
    date_dt = datetime.datetime.strptime(q, '%Y-%m-%d')
    print(date_dt)
    date_fool_moon = (ephem.next_full_moon(date_dt))
    return str(date_fool_moon)
Esempio n. 26
0
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
Esempio n. 27
0
def get_full_moon(input_string):
    match_data = re.search('\d{4}\-\d{2}\-\d{2}', input_string)

    if match_data:
        return ephem.next_full_moon(match_data.group())
    else:
        return "Bad data format"
Esempio n. 28
0
def run():
    ''' Get the first fall sub 29 and when the nearest full moon was that year
    '''
    cursor.execute(''' SELECT year, min(day), min(extract(doy from day))
    from alldata_ia where
    station = 'IA0200' and low < 29 and month > 6 GROUP by year ORDER
    by year ASC''')
    juliandays = []
    moondiff = []
    for row in cursor:
        juliandays.append( row[2] )
        myloc.date = "%s/%s/%s" % (row[1].year, row[1].month, row[1].day)
        
        lastd = s2dt(ephem.previous_full_moon(myloc.date)).date()
        today = row[1]
        nextd = s2dt(ephem.next_full_moon(myloc.date)).date()
        forward = (nextd - today).days
        backward = (today - lastd).days
        if backward == forward:
            moondiff.append(backward)
        elif backward < forward:
            moondiff.append( backward )
        elif forward < backward:
            moondiff.append( 0 - forward)
            
    return moondiff, juliandays
Esempio n. 29
0
    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
Esempio n. 30
0
 def timeToFullMoon(self):
     '''
     This function calculates the time to the next full moon.
     @returns: The time to full moon in decimal days.
     '''
     next_full_moon = ephem.next_full_moon(self._observer.date)
     return next_full_moon - self._observer.date
Esempio n. 31
0
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 '
Esempio n. 32
0
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
Esempio n. 33
0
    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
Esempio n. 34
0
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
Esempio n. 35
0
def moon_command(bot, update):
    user_text = update.message.text
    x = re.search(date_regex_string, user_text)
    date_for_check = x.group()
    res = ephem.next_full_moon(date_for_check).datetime()
    update.message.reply_text("Ближайшее полнолуние после {}: {}".format(
        date_for_check, res.strftime('%d %B %Y %H:%M')))
Esempio n. 36
0
def get_full_moon(text_message):
    try:
        date = get_date(text_message)
        return ephem.next_full_moon(date)
    except Exception as err:
        if str(err) == "incorrect":
            return "Пиши вопрос ввиде: \"Когда ближайшее полнолуние после yyyy-mm-dd?\""
Esempio n. 37
0
def fullmoonoctober_search(bot, update):
    user_query_fm_oct = update.message.text.lower()
    print('user_query_fm_oct', user_query_fm_oct)
    nearest_fm_oct = ephem.next_full_moon('2016/10/01')
    print('nearest_fm_oct', nearest_fm_oct)
    answer_output_for_bot_format = 'Полнолуние состоится: {}'.format(
        nearest_fm_oct) + ' ' + 'Не опаздывайте!'
    bot.sendMessage(update.message.chat_id, answer_output_for_bot_format)
Esempio n. 38
0
 def _get_next_fullmoon(self):
     """
     Return the date and time of the next full moon
     @return : the next full moon daytime
     """
     now = datetime.datetime.today()
     nextfullmoon = ephem.next_full_moon(now)
     return nextfullmoon
Esempio n. 39
0
def easter(day):
    if day.weekday() in frozenset([sunday, monday]) and 3 <= day.month <= 4:
        spring_equinox = ephem.next_equinox(str(day.year))
        full_moon = ephem.next_full_moon(spring_equinox)
        easter_day = full_moon.datetime().date() + timedelta(days=1)
        while easter_day.weekday() != sunday:
            easter_day += timedelta(days=1)
        if day in [easter_day, easter_day + timedelta(days=1)]:
            yield "Valstybinė šventė: Velykos"
Esempio n. 40
0
def full_moon_from_to(start_date, end_date):
  "Print the full moons"
  # Not used,
  # TODO: compute lunar eclipse at full moon
  #       and solar eclipse on new moon.
  date = start_date
  next_day = datetime.timedelta(days=1)
  while date < end_date:
      fm = ephem.next_full_moon(date).datetime()
      print("full moon on %04d-%02d-%02d" % (
        fm.year, fm.month, fm.day))
      date = fm + next_day
Esempio n. 41
0
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"🌑"
Esempio n. 42
0
def monthly_ephem(city, year, month):
  # Return a short string containing full_moon day
  # and sun rise, sun set for (city, date=(year, month, 1)).
  # moon_phase is 0..29, 0 new moon, 15 is new moon.
  # moon_fm is 'FM', 'NM' etc for the given date.
  date = datetime.datetime(year, month, 1)
  next_full_moon = ephem.next_full_moon(date).datetime()
  (sunrise, sunset, moon_phase, moon_fm) = ephem_one_day(city, date)
  # moon_phase is not used, only next_full_moon date is printed.
  return "M:%2d Sun:%02d:%02d-%02d:%02d" % (
    next_full_moon.day,
    sunrise.hour, sunrise.minute,
    sunset.hour, sunset.minute)
Esempio n. 43
0
 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])
Esempio n. 44
0
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 ''
Esempio n. 45
0
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
Esempio n. 46
0
    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
Esempio n. 47
0
 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
Esempio n. 48
0
def find_azimuths(observer):
    riseset = {}

    # Find sunrise and sunset:
    riseset['sun'] = find_rise_set(observer, ephem.Sun())

    # Now find the full moon closest to the date,
    # which may be the next full moon or the previous one.
    lastfull = ephem.previous_full_moon(observer.date)
    nextfull = ephem.next_full_moon(observer.date)
    now = ephem.now()
    if now - lastfull > nextfull - now:
        observer.date = nextfull
    else:
        observer.date = lastfull

    riseset['full moon'] = find_rise_set(observer, ephem.Moon())

    return riseset
Esempio n. 49
0
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())
Esempio n. 50
0
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
Esempio n. 51
0
#!/usr/bin/env python
# Author: Mike R
# Will require install of PyEphem: pip install ephem
# Gets list of full and new moons for the year

import ephem

d1 = ephem.next_full_moon("2016")

month = 1
while month < 13:

    print "------------------------------"
    if month == 1:
        print "January"
    elif month == 2:
        print "February"
    elif month == 3:
        print "March"
    elif month == 4:
        print "April"
    elif month == 5:
        print "May"
    elif month == 6:
        print "June"
    elif month == 7:
        print "July"
    elif month == 8:
        print "August"
    elif month == 9:
        print "September"
Esempio n. 52
0
local.elevation=231
local.date=now
#local.date="2015-04-24 20:00:55"
local.horizon='0:34'

nextSet = ephem.localtime(local.next_setting(sun))
nextRise = ephem.localtime(local.next_rising(sun))
prevSet = ephem.localtime(local.previous_setting(sun))
prevRise = ephem.localtime(local.previous_rising(sun))

print("Previous sunrise in KC was: ",ephem.localtime(local.previous_rising(sun)))
#logger.debug("Previous sunrise in KC was: ",ephem.localtime(local.previous_rising(sun)))
print("Previous sunset in KC was: ",ephem.localtime(local.previous_setting(sun)))
print("Next sunrise in KC will be: ",ephem.localtime(local.next_rising(sun)))
print("Next sunset in KC will be: ",ephem.localtime(local.next_setting(sun)))
print("Next Full Moon will be: " ,ephem.localtime(ephem.next_full_moon(now)))
print("Next New Moon will be: " ,ephem.localtime(ephem.next_new_moon(now)))
print("Next Solstice will be: " ,ephem.localtime(ephem.next_solstice(now)))
print("Next Equinox will be: " ,ephem.localtime(ephem.next_equinox(now)))
print("Sunrise:" ,local.next_rising(ephem.Sun()).datetime())
print("Sunset:" ,local.next_setting(ephem.Sun()).datetime())
next_sunrise_datetime = local.next_rising(ephem.Sun()).datetime()
next_sunset_datetime = local.next_setting(ephem.Sun()).datetime()

# If it is daytime, we will see a sunset sooner than a sunrise.
it_is_day = next_sunset_datetime < next_sunrise_datetime
print("It's day." if it_is_day else "It's night.")

# If it is nighttime, we will see a sunrise sooner than a sunset.
it_is_night = next_sunrise_datetime < next_sunset_datetime
print("It's night." if it_is_night else "It's day.")
Esempio n. 53
0
#!/usr/bin/python
# Print next moon quarter (requires PyEphem)
# 2014-07-08

import ephem

n = ephem.now()

# Unicode symbols are for inverted text (white on black):
p = [[ephem.next_full_moon(n),"🌑 Vollmond"],
[ephem.next_last_quarter_moon(n),"🌓 Letztes Viertel"],
[ephem.next_new_moon(n),"🌕 Neumond"],
[ephem.next_first_quarter_moon(n),"🌗 Erstes Viertel"]]

p.sort()

a = p[0]

h = 24*(a[0]-n)

def nat(h):
	h2 = round(h)
	if h > 24:
		d = h2//24
		if d > 1:
			dh = "%u Tagen" % d
		else:
			dh = "einem Tag"
		hh = h2 - 24*d
		if hh > 1:
			hhh = "%u Stunden" % hh
Esempio n. 54
0
def main():

    sun = ephem.Sun()
    moon = ephem.Moon()

    # define observer
    home = ephem.Observer()
    home.date = ephem.date(datetime.utcnow())
    home.lat, home.lon = '50.46', '9.61'

    sun.compute(home)
    sunrise, sunset = (home.next_rising(sun),
                       home.next_setting(sun))
    moon.compute(home)
    moonrise, moonset = (home.next_rising(moon),
                       home.next_setting(moon))
    home.horizon = '-6'
    m6_start, m6_end = (home.next_rising(sun, use_center=True),
                        home.next_setting(sun, use_center=True))
    home.horizon = '-12'
    m12_start, m12_end = (home.next_rising(sun, use_center=True),
                          home.next_setting(sun, use_center=True))
    home.horizon = '-18'
    m18_start, m18_end = (home.next_rising(sun, use_center=True),
                          home.next_setting(sun, use_center=True))

    print home.date

    e = {}
    e[sunrise] =   " Sunrise:                      "
    e[sunset] =    " Sunset:                       "
    e[moonrise] =  " Moonrise:                     "
    e[moonset] =   " Moonset:                      "
    e[m6_start] =  " Civil twilight starts:        "
    e[m6_end] =    " Civil twilight ends:          "
    e[m12_start] = " Nautical twilight starts:     "
    e[m12_end] =   " Nautical twilight ends:       "
    e[m18_start] = " Astronomical twilight starts: "
    e[m18_end] =   " Astronomical twilight ends:   "

    for time in sorted(e.keys()):
        print e[time], ephem.localtime(time).ctime()

    # Here start the moon specific data

    print " ---"
    print " Moon phase: %d%% " % moon.phase

    e = {}
    e1 = ephem.previous_new_moon(home.date)
    e[e1] = " Previous new moon:            "
    e1 = ephem.previous_first_quarter_moon(home.date)
    e[e1] = " Previous first quarter moon:  "
    e1 = ephem.previous_full_moon(home.date)
    e[e1] = " Previous full moon:           "
    e1 = ephem.previous_last_quarter_moon(home.date)
    e[e1] = " Previous last quarter moon:   "

    e1 = ephem.next_new_moon(home.date)
    e[e1] = " Next new moon:                "
    e1 = ephem.next_first_quarter_moon(home.date)
    e[e1] = " Next first quarter moon:      "
    e1 = ephem.next_full_moon(home.date)
    e[e1] = " Next full moon:               "
    e1 = ephem.next_last_quarter_moon(home.date)
    e[e1] = " Next last quarter moon:       "

    for time in sorted(e.keys()):
        print e[time], ephem.localtime(time).ctime()
Esempio n. 55
0
sunset  = observer.next_setting   (ephem.Sun()) #Sunset

data['sunrise'] = str(ephem.localtime(sunrise))
data['noon']    = str(ephem.localtime(noon))
data['sunset']  = str(ephem.localtime(sunset))

# observer.horizon = '-6' # civil twilight
# civilian_twilight_start = observer.previous_rising(ephem.Sun())
# civilian_twilight_end = observer.next_setting(ephem.Sun())

# observer.horizon = '-12' # nautical twilight
# nautical_twilight_start = observer.previous_rising(ephem.Sun())
# nautical_twilight_end = observer.next_setting(ephem.Sun())

# observer.horizon = '-18' # astronomical twilight
# astronomical_twilight_start = observer.previous_rising(ephem.Sun())
# astronomical_twilight_end = observer.next_setting(ephem.Sun())

data['moon'] = {}
data['moon']['radius'] = ephem.moon_radius
data['moon']['previous_new_moon'] = str(ephem.localtime(ephem.previous_new_moon(time)))
data['moon']['next_new_moon'] = str(ephem.localtime(ephem.next_new_moon(time)))
data['moon']['previous_first_quarter_moon'] = str(ephem.localtime(ephem.previous_first_quarter_moon(time)))
data['moon']['next_first_quarter_moon'] = str(ephem.localtime(ephem.next_first_quarter_moon(time)))
data['moon']['previous_full_moon'] = str(ephem.localtime(ephem.previous_full_moon(time)))
data['moon']['next_full_moon'] = str(ephem.localtime(ephem.next_full_moon(time)))
data['moon']['previous_last_quarter_moon'] = str(ephem.localtime(ephem.previous_last_quarter_moon(time)))
data['moon']['next_last_quarter_moon'] = str(ephem.localtime(ephem.next_last_quarter_moon(time)))

print json.dumps(data)
Esempio n. 56
0
    def do_thread_loop(self):
        while(self.running):
            if ( self.mqtt_connected ):    
                nowtime=datetime.datetime.now()
                if(nowtime.year != self.year):
                    self.year = nowtime.year
                    self.mqttc.publish("/raw/clock/year", self.year, retain=True)
                if(nowtime.month != self.month):
                    self.month = nowtime.month
                    self.mqttc.publish("/raw/clock/month", self.month, retain=True)
                if(nowtime.day != self.day):
                    self.day = nowtime.day
                    self.mqttc.publish("/raw/clock/day", self.day, retain=True)
                    self.weekday=nowtime.weekday()
                    self.mqttc.publish("/raw/clock/weekday", self.weekday, retain=True)
                    self.utc_sunrise=self.observer.next_rising(self.sun)
#                    self.mqttc.publish("/raw/clock/utc_sunrise", str(self.utc_sunrise), retain=True)
                    self.sunrise=ephem.localtime(self.observer.next_rising(self.sun))
                    self.mqttc.publish("/raw/clock/sunrise", str(self.sunrise), retain=True)
                    self.utc_sunset=self.observer.next_setting(self.sun)
#                    self.mqttc.publish("/raw/clock/utc_sunset", str(self.utc_sunset), retain=True)
                    self.sunset=ephem.localtime(self.observer.next_setting(self.sun))
                    self.mqttc.publish("/raw/clock/sunset", str(self.sunset), retain=True)
                    self.utc_moonrise=self.observer.next_rising(self.moon)
#                    self.mqttc.publish("/raw/clock/utc_moonrise", str(self.utc_moonrise), retain=True)
                    self.moonrise=ephem.localtime(self.observer.next_rising(self.moon))
                    self.mqttc.publish("/raw/clock/moonrise", str(self.moonrise), retain=True)
                    self.utc_moonset=self.observer.next_setting(self.moon)
#                    self.mqttc.publish("/raw/clock/utc_moonset", str(self.utc_moonset), retain=True)
                    self.moonset=ephem.localtime(self.observer.next_setting(self.moon))
                    self.mqttc.publish("/raw/clock/moonset", str(self.moonset), retain=True)
                    self.nextnewmoon=ephem.next_new_moon(nowtime)
                    self.mqttc.publish("/raw/clock/nextnewmoon", str(self.nextnewmoon), retain=True) 
                    self.nextfirstquartermoon=ephem.next_first_quarter_moon(nowtime)
                    self.mqttc.publish("/raw/clock/nextfirstquartermoon", str(self.nextfirstquartermoon), retain=True)
                    self.nextlastquartermoon=ephem.next_last_quarter_moon(nowtime)
                    self.mqttc.publish("/raw/clock/nextlastquartermoon", str(self.nextlastquartermoon), retain=True)
                    self.nextfullmoon=ephem.next_full_moon(nowtime)
                    self.mqttc.publish("/raw/clock/nextfullmoon", str(self.nextfullmoon), retain=True)                   
                if(nowtime.hour != self.mil_hour):
                    self.mil_hour = nowtime.hour
                    self.hour = self.mil_hour % 12
                    if (self.hour == 0):
                        self.hour = 12
                    self.mqttc.publish("/raw/clock/hour", self.hour, retain=True)
                    self.mqttc.publish("/raw/clock/militaryhour", self.mil_hour, retain=True)
                    if(self.mil_hour > 11):
                        self.ampm = "PM"
                    else:
                        self.ampm = "AM"
                    if((self.mil_hour == 12) or (self.mil_hour == 0)):
                        self.mqttc.publish("/raw/clock/ampm", self.ampm, retain=True)
                if(nowtime.minute != self.minute):
                    self.minute = nowtime.minute
                    self.mqttc.publish("/raw/clock/minute", self.minute, retain=True)
                if(nowtime < self.sunrise):        # is this right???
                    temp = "set" 
                elif(nowtime > self.sunset):
                    temp="set"
                else:
                    temp="rise"
                if(temp != self.sunstate):
                    self.sunstate=temp
                    self.mqttc.publish("/raw/clock/sunstate", self.sunstate, retain=True)
                if ( self.interval ):
                    print "Waiting ", self.interval, " seconds for next update."
                    time.sleep(self.interval)
Esempio n. 57
0
	def OnDateSelect(self, evt):

		f = open(r'/etc/nx.lat')  # Lat/lon files for Navigatrix
		lat = f.readline(12)
		f.close()

		f = open(r'/etc/nx.lon')
		lon = f.readline(12)
		f.close()

		lat = float(lat)
		lon = float(lon)

		degrees = int(lat)
		mnn = (lat - degrees) * 60
		minutes = int(mnn)
		seconds = round(((mnn - minutes) * 60), 3)
		lat = str(degrees) + str(minutes) + str(seconds)

		degrees = int(lon)
		mnn = (lon - degrees) * 60
		minutes = int(mnn)
		seconds = round(((mnn - minutes) * 60), 3)
		lon = str(degrees) + str(minutes) + str(seconds)

		here = ephem.Observer()
		here.lat = lat
		here.lon = lon

		here.pressure = 0  # barometric pressure not factored
		here.horizon = '-0:34'  # fudge factor from the US Navel Observatory
		here.elevation = 2.0  # 2 Meters elevation
		here.temp = 25.0  # and a balmy 25 degrees

		cal = evt.GetEventObject()

		year = (str(self.cal.GetDate().GetYear()))
		month = (str(self.cal.GetDate().GetMonth() + 1))
		day = (str(self.cal.GetDate().GetDay()))
		hour = strftime("%H:%M:%S", gmtime())

		datefig = year + '/' + month + '/' + day + ' ' + hour

		here.date = datefig

		sun = ephem.Sun(here)
		moon = ephem.Moon(here)

		moon.compute(here)

		#
		# Moon Rise
		#
		#        mrtime = str(here.next_rising(moon))

		mrtime = here.next_rising(moon)
		lt = ephem.localtime(mrtime)
		mrtime = str(lt).split()
		mrtime = mrtime[1].split(".")
		self.mrtime.SetLabel(str(mrtime[0]))

		mraz = str(moon.az).partition(':')
		self.mraz.SetLabel(str(mraz[0]) + u'\u00B0 from North')
		#
		# Moonset        moon.compute(here)
		#
		#
		mstime = here.next_setting(moon)
		lt = ephem.localtime(mstime)
		mstime = str(lt).split()
		mstime = mstime[1].split(".")
		self.mstime.SetLabel(mstime[0])

		msaz = str(moon.az).partition(':')
		self.msaz.SetLabel(str(msaz[0]) + u'\u00B0 from North')

		#
		# Moon Phase
		# TODO Clearly these numbers are pulled out of a hat.
		# they are a very rough approximation of the phases and
		# do not account for waxing and waning
		phasepercent = int(moon.moon_phase * 100)
		self.phasepercent.SetLabel(str(phasepercent) + " %")

		if phasepercent <= 2.0:
			moonphase = "New Moon"
		if 2.1 < phasepercent <= 20.0:
			moonphase = "Crescent"
		if 20.1 < phasepercent <= 60.0:
			moonphase = "Quarter Moon"
		if 60.1 < phasepercent <= 95.0:
			moonphase = "Gibbous"
		if phasepercent > 95.1:
			moonphase = "Full Moon"
		self.moonphase.SetLabel(moonphase)
		#
		# New Moon Date
		#
		newmoondate = ephem.next_new_moon(datefig)
		lt = ephem.localtime(newmoondate)
		newmoondate = str(lt).split()
		newmoonhour = newmoondate[1].split(".")

		self.newmoondate.SetLabel(str(newmoondate[0]))
		self.newmoonhour.SetLabel(str(newmoonhour[0]))
		#
		# Full Moon Date
		#
		fullmoondate = ephem.next_full_moon(datefig)
		lt = ephem.localtime(fullmoondate)
		fullmoondate = str(lt).split()
		fullmoonhour = fullmoondate[1].split(".")

		self.fullmoondate.SetLabel(str(fullmoondate[0]))
		self.fullmoonhour.SetLabel(str(fullmoonhour[0]))
		#
		# Sun Rise
		#

		sun.compute(here)

		srtime = here.next_rising(sun)
		lt = ephem.localtime(srtime)
		srtime = str(lt).split()
		srtime = srtime[1].split(".")
		self.srtime.SetLabel(srtime[0])

		sraz = str(sun.az).partition(':')
		self.sraz.SetLabel(str(sraz[0]) + u'\u00B0 from North')
		#
		# High Noon
		#
		sntime = here.next_transit(sun)
		lt = ephem.localtime(sntime)
		sntime = str(lt).split()
		sntime = sntime[1].split(".")
		self.sntime.SetLabel(sntime[0])

		snaltitude = str(sun.alt).partition(':')
		self.snaltitude.SetLabel(str(snaltitude[0]) + u'\u00B0 above Horizon')
		#
		# Sun Set
		#
		sstime = here.next_setting(sun)
		lt = ephem.localtime(sstime)
		sstime = str(lt).split()
		sstime = sstime[1].split(".")
		self.sstime.SetLabel(sstime[0])

		ssaz = str(sun.az).partition(':')
		self.ssaz.SetLabel(str(ssaz[0]) + u'\u00B0 from North')
Esempio n. 58
0
now = datetime.now()

#Past Moon phases
d5 = ephem.previous_new_moon(now)
d6 = ephem.previous_first_quarter_moon(now)
d7 = ephem.previous_full_moon(now)
d8 = ephem.previous_last_quarter_moon(now)
print
print (d5), "	| Previous new Moon"
print (d6), "	| Previous quarter Moon"
print (d7), "	| Previous full Moon"
print (d8), "	| Previous last quarter Moon"
print

#Next Moon phases
d1 = ephem.next_full_moon(now)
d2 = ephem.next_new_moon(now)
d3 = ephem.next_first_quarter_moon(now)
d4 = ephem.next_last_quarter_moon(now)
print (d2), "	| Next new Moon"
print (d3), "	| Next quarter Moon"
print (d1), "	| Next full Moon"
print (d4), "	| Next last quarter Moon"
print

m=ephem.Moon(now)
print "Moon is actually:", (ephem.constellation(m))

quit()
# MOON DATA
moonrise = observer.previous_rising(ephem.Moon())
moonnoon    = observer.next_transit   (ephem.Moon())
moonset  = observer.next_setting   (ephem.Moon())
data['moon']['rise'] = calendar.timegm(moonrise.datetime().utctimetuple())
data['moon']['noon']    = calendar.timegm(moonnoon.datetime().utctimetuple())
data['moon']['set']  = calendar.timegm(moonset.datetime().utctimetuple())
data['moon']['radius'] = ephem.moon_radius

previous_new_moon = ephem.previous_new_moon(time)
next_new_moon = ephem.next_new_moon(time)
previous_first_quarter_moon = ephem.previous_first_quarter_moon(time)
next_first_quarter_moon = ephem.next_first_quarter_moon(time)
previous_full_moon = ephem.previous_full_moon(time)
next_full_moon = ephem.next_full_moon(time)
previous_last_quarter_moon = ephem.previous_last_quarter_moon(time)
next_last_quarter_moon = ephem.next_last_quarter_moon(time)

data['moon']['previous_new_moon'] = calendar.timegm(previous_new_moon.datetime().utctimetuple())
data['moon']['next_new_moon'] = calendar.timegm(next_new_moon.datetime().utctimetuple())
data['moon']['previous_first_quarter_moon'] = calendar.timegm(previous_first_quarter_moon.datetime().utctimetuple())
data['moon']['next_first_quarter_moon'] = calendar.timegm(next_first_quarter_moon.datetime().utctimetuple())
data['moon']['previous_full_moon'] = calendar.timegm(previous_full_moon.datetime().utctimetuple())
data['moon']['next_full_moon'] = calendar.timegm(next_full_moon.datetime().utctimetuple())
data['moon']['previous_last_quarter_moon'] = calendar.timegm(previous_last_quarter_moon.datetime().utctimetuple())
data['moon']['next_last_quarter_moon'] = calendar.timegm(next_last_quarter_moon.datetime().utctimetuple())

moon = ephem.Moon()
moon.compute(observer)