Esempio n. 1
0
def solsticio_pyephem(lat, anio, huso):
    inicio_utc = datetime2utc(datetime(anio, 1, 1), huso)
    if float(lat) < 0:
        return ephem.next_winter_solstice(inicio_utc)  # Hemisferio Sur
    elif float(lat) > 0:
        return ephem.next_summer_solstice(inicio_utc)  # Hemisferio Norte
    raise Exception("Por ahora no soporto ubicaciones sobre el Ecuador :(")
Esempio n. 2
0
def s2l(solarDate: ephem.Date, location: ephem.Observer,
        timezone: int) -> LUNAR_contract:
    solarDate += timezone * ephem.hour  # so we are working in the correct timezone

    lunar_leap = False

    previousNewMoon = ephem.previous_new_moon(solarDate)
    lunarDay = solarDate.day - ephem.Date(previousNewMoon).datetime().day + 1

    # Dong chi nam truoc
    previousWinterSolstice = ephem.previous_winter_solstice(solarDate)
    # Dong chi nam sau
    nextWinterSolstice = ephem.next_winter_solstice(solarDate)

    dayInLunarYear = ephem.previous_new_moon(
        nextWinterSolstice) - ephem.previous_new_moon(previousWinterSolstice)

    diff = int(dayInLunarYear / 29.)

    lunarMonth = diff + 11

    lunarYear = solarDate.year

    if dayInLunarYear > 365:
        lunar_leap = (lunarMonth == find_lunar_month_between(
            previousWinterSolstice, nextWinterSolstice))

    print(dayInLunarYear, previousWinterSolstice, nextWinterSolstice)
    return tuple(date(lunarYear, lunarMonth, lunarDay), lunar_leap)
Esempio n. 3
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. 4
0
def astronomical_dates(year):
    y = str(year)
    march = ephem.next_spring_equinox(y).datetime().date()
    june = ephem.next_summer_solstice(y).datetime().date()
    sept = ephem.next_autumn_equinox(y).datetime().date()
    dec = ephem.next_winter_solstice(y).datetime().date()
    return dict(march=march, june=june, sept=sept, dec=dec)
Esempio n. 5
0
def EquinoxSolsticeJD(year, angle):
    if 0 <= angle < 90:
        date = ephem.next_vernal_equinox(year)
    elif 90 <= angle < 180:
        date = ephem.next_summer_solstice(year)
    elif 180 <= angle < 270:
        date = ephem.next_autumn_equinox(year)
    else:
        date = ephem.next_winter_solstice(year)
    JD = ephem.julian_date(date)
    return JD
Esempio n. 6
0
def sol(jotape_bot, last_chat_id):
    # Brasilia
    bsb = ephem.Observer()
    bsb.lat, bsb.lon = '-15.6982196', '-48.1082429'
    bsb.horizon = '-6'  # Civil twilight -6 graus em relação ao centro do sol
    bsb.date = datetime.datetime.utcnow()
    nascer = bsb.next_rising(ephem.Sun()).datetime().replace(tzinfo=pytz.utc)
    zenite = bsb.next_transit(ephem.Sun()).datetime().replace(tzinfo=pytz.utc)
    por = bsb.next_setting(ephem.Sun()).datetime().replace(tzinfo=pytz.utc)

    unascer = bsb.previous_rising(
        ephem.Sun()).datetime().replace(tzinfo=pytz.utc)
    uzenite = bsb.previous_transit(
        ephem.Sun()).datetime().replace(tzinfo=pytz.utc)
    upor = bsb.previous_setting(
        ephem.Sun()).datetime().replace(tzinfo=pytz.utc)
    jotape_bot.send_message(
        last_chat_id,
        "Último\nNascer do Sol: %s\n Zênite: %s\n Pôr-do-sol: %s\n---\nPróximo\nNascer do Sol: %s\n Zênite: %s\n Pôr-do-sol: %s\n"
        % (unascer.astimezone(pytz.timezone('America/Sao_Paulo')),
           uzenite.astimezone(pytz.timezone('America/Sao_Paulo')),
           upor.astimezone(pytz.timezone('America/Sao_Paulo')),
           nascer.astimezone(pytz.timezone('America/Sao_Paulo')),
           zenite.astimezone(pytz.timezone('America/Sao_Paulo')),
           por.astimezone(pytz.timezone('America/Sao_Paulo'))))

    dts = [
        ('Outono', ephem.next_vernal_equinox(
            datetime.datetime.utcnow()).datetime().replace(tzinfo=pytz.utc)),
        ('Inverno', ephem.next_summer_solstice(
            datetime.datetime.utcnow()).datetime().replace(tzinfo=pytz.utc)),
        ('Verão', ephem.next_winter_solstice(
            datetime.datetime.utcnow()).datetime().replace(tzinfo=pytz.utc)),
        ('Primavera', ephem.next_autumnal_equinox(
            datetime.datetime.utcnow()).datetime().replace(tzinfo=pytz.utc))
    ]
    lista = sorted(dts, key=lambda x: x[1])
    s = ""
    for d in lista:
        s = s + ("%s - %s\n" %
                 (d[0], d[1].astimezone(pytz.timezone('America/Sao_Paulo'))))

    jotape_bot.send_message(last_chat_id, s)
Esempio n. 7
0
def seasonPhase(date):
    season = ""
    nss = ephem.next_summer_solstice(date).datetime()
    nae = ephem.next_autumnal_equinox(date).datetime()
    nws = ephem.next_winter_solstice(date).datetime()
    nve = ephem.next_vernal_equinox(date).datetime()
    if nss > nae:
        season = "Summer"
    if nae > nws:
        season = "Autumn"
    if nws > nve:
        season = "Winter"
    if nve > nss:
        season = "Spring"
    if date == nss.replace(hour=0, minute=0, second=0, microsecond=0):
        season = "Summer Solstice %s" % nss.strftime('%Y.%m.%d %H:%M:%S')
    if date == nae.replace(hour=0, minute=0, second=0, microsecond=0):
        season = "Autumnal equinox %s" % nae.strftime('%Y.%m.%d %H:%M:%S')
    if date == nws.replace(hour=0, minute=0, second=0, microsecond=0):
        season = "Winter solstice %s" % nws.strftime('%Y.%m.%d %H:%M:%S')
    if date == nve.replace(hour=0, minute=0, second=0, microsecond=0):
        season = "Vernal equinox %s" % nve.strftime('%Y.%m.%d %H:%M:%S')
    return season
Esempio n. 8
0
 def update(self):
     date = ephem.Date(datetime.now().date())
     self.seasondata.update({
         'Autumnal (Fall) Equinox':
         ephem.next_autumn_equinox(date).datetime().date()
     })
     self.moondata.update({
         'First Quarter':
         ephem.next_first_quarter_moon(date).datetime().date()
     })
     self.moondata.update(
         {'Full Moon': ephem.next_full_moon(date).datetime().date()})
     self.moondata.update({
         'Last Quarter':
         ephem.next_last_quarter_moon(date).datetime().date()
     })
     self.moondata.update(
         {'New Moon': ephem.next_new_moon(date).datetime().date()})
     self.seasondata.update({
         'Vernal (Spring) Equinox':
         ephem.next_spring_equinox(date).datetime().date()
     })
     self.seasondata.update({
         'Summer Solstice':
         ephem.next_summer_solstice(date).datetime().date()
     })
     self.seasondata.update({
         'Winter Solstice':
         ephem.next_winter_solstice(date).datetime().date()
     })
     moon_keys = sorted(self.moondata.keys(),
                        key=lambda y: (self.moondata[y]))
     moon_keys.reverse()
     b = {}
     state1 = True
     while moon_keys:
         a = moon_keys.pop()
         b.update({a: self.moondata[a]})
         if self.moondata[a] != datetime.now().date() and state1:
             self.nextphase = [
                 a, self.moondata[a],
                 daysaway(self.moondata[a])
             ]
             state1 = False
             if self.moondata[a] == datetime.now().date():
                 self.currentphase = a
             ##### elif
     self.moondata = b
     season_keys = sorted(self.seasondata.keys(),
                          key=lambda y: (self.seasondata[y]))
     season_keys.reverse()
     b = {}
     state2 = True
     while season_keys:
         a = season_keys.pop()
         b.update({a: self.seasondata[a]})
         if self.seasondata[a] != datetime.now().date() and state2:
             self.nextseason = [
                 a, self.seasondata[a],
                 daysaway(self.seasondata[a])
             ]
             state2 = False
     self.seasondata = b
     if self.nextphase[0] == 'Last Quarter' and datetime.now().date(
     ) < self.nextphase[1]:
         self.currentphase = 'Waning Gibbus'
     if self.nextphase[0] == 'Last Quarter' and datetime.now().date(
     ) == self.nextphase[1]:
         self.currentphase = 'Last Quarter'
     if self.nextphase[0] == 'New Moon' and datetime.now().date(
     ) < self.nextphase[1]:
         self.currentphase = 'Waning Crescent'
     if self.nextphase[0] == 'New Moon' and datetime.now().date(
     ) == self.nextphase[1]:
         self.currentphase = 'New Moon'
     if self.nextphase[0] == 'First Quarter' and datetime.now().date(
     ) < self.nextphase[1]:
         self.currentphase = 'Waxing Crescent'
     if self.nextphase[0] == 'First Quarter' and datetime.now().date(
     ) == self.nextphase[1]:
         self.currentphase = 'First Quarter'
     if self.nextphase[0] == 'Full Moon' and datetime.now().date(
     ) < self.nextphase[1]:
         self.currentphase = 'Waxing Gibbus'
     if self.nextphase[0] == 'Full Moon' and datetime.now().date(
     ) == self.nextphase[1]:
         self.currentphase = 'Full Moon'
Esempio n. 9
0
def Num_of_Dun(attribute,round): #attribute = 1(阴),0(阳);round = 局数
    if attribute == 1:
        print(Yin)
    elif attribute == 0:
        print(Yang)
    else:
        print('Error!')
print(Num_of_Dun(3,0))

import datetime
import dateutil.parser
import ephem
import time
years = time.strftime('%Y',time.localtime(time.time()))
xz = ephem.next_summer_solstice(years)
dz = ephem.next_winter_solstice(years)
cf = ephem.next_vernal_equinox(years)
qf = ephem.next_autumnal_equinox(years)
xz = str(xz)
dz = str(dz)
cf = str(cf)
qf = str(qf)
print('Now(UTC+8) ' + time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())))
print('Summer_solstice    GMT=' + xz)
print('Winter_solstice    GMT=' + dz)
print('Vernal_equinox     GMT=' + cf)
print('Autumnal_equinox   GMT=' + qf)
def getDateTime(s):
    d = dateutil.parser.parse(s)
    return d
print(getDateTime(xz) + datetime.timedelta(hours = 8))
Esempio n. 10
0
    def update_daily_info(self):
        # current time, used in many of following calculations
        rn = datetime.datetime.now(tz=pytz.timezone(self.otto_info['tz']))

        # get sun times for 3 days
        otto_sun_yesterday = astral.sun.sun(self.otto_obs,
                                            datetime.datetime.today() -
                                            datetime.timedelta(days=1),
                                            tzinfo=self.otto_info['tz'])
        otto_sun_today = astral.sun.sun(self.otto_obs,
                                        datetime.datetime.today(),
                                        tzinfo=self.otto_info['tz'])
        otto_sun_tomorrow = astral.sun.sun(self.otto_obs,
                                           datetime.datetime.today() +
                                           datetime.timedelta(days=1),
                                           tzinfo=self.otto_info['tz'])

        # compute day lengths
        day_length_yesterday = otto_sun_yesterday[
            'sunset'] - otto_sun_yesterday['sunrise']
        self.day_length_yesterday_str = self.daylen_tostr(day_length_yesterday)
        day_length_today = otto_sun_today['sunset'] - otto_sun_today['sunrise']
        self.day_length_today_str = self.daylen_tostr(day_length_today)
        day_length_tomorrow = otto_sun_tomorrow['sunset'] - otto_sun_tomorrow[
            'sunrise']
        self.day_length_tomorrow_str = self.daylen_tostr(day_length_tomorrow)

        # compute how much longer today was vs yesterday, change delta text color
        self.yesterday_today_delta_str = self.daydelta_tostr(
            day_length_today - day_length_yesterday)
        if self.yesterday_today_delta_str[1] == '+':
            self.ids.yest_delta.color = (0, 1, 0, self.alpha)
        else:
            self.ids.yest_delta.color = (1, 0, 0, self.alpha)

        # compute how much longer tomorrow will be vs today, change delta text color
        self.today_tomorrow_delta_str = self.daydelta_tostr(
            day_length_tomorrow - day_length_today)
        if self.today_tomorrow_delta_str[1] == '+':
            self.ids.tom_delta.color = (0, 1, 0, self.alpha)
        else:
            self.ids.tom_delta.color = (1, 0, 0, self.alpha)

        # update today's date
        self.date = rn.strftime('%Y.%m.%d')

        # compute PST or PDT completion percentage
        daylight_trans_dates = [
            x.date() for x in pytz.timezone('US/Pacific')._utc_transition_times
            if x.year >= rn.year - 1 and x.year <= rn.year + 1
        ]  # has daylight times last year to next year
        if rn.date(
        ) < daylight_trans_dates[2]:  # before this year's spring forward)
            # useful dates are last year's fall back and this year's spring forward. currently PST
            pst_duration_days = daylight_trans_dates[2] - daylight_trans_dates[
                1]
            pst_completed_days = rn.date() - daylight_trans_dates[1]
            self.pdt_or_pst_completion_str = f'PST is {pst_completed_days/pst_duration_days*100:.2f}% done.'
        elif rn.date(
        ) < daylight_trans_dates[3]:  # between [spring forward and fall back)
            # useful dates: this year's spring forward, fall back. currently PDT :)
            pdt_duration_days = daylight_trans_dates[3] - daylight_trans_dates[
                2]
            pdt_completed_days = rn.date() - daylight_trans_dates[2]
            self.pdt_or_pst_completion_str = f'PDT is {pdt_completed_days/pdt_duration_days*100:.2f}% done.'
        else:  # you're after this year's fall back]
            # useful dates: this year's fall back, next year's spring forward. currently PST
            pst_duration_days = daylight_trans_dates[4] - daylight_trans_dates[
                3]
            pst_completed_days = rn.date() - daylight_trans_dates[3]
            self.pdt_or_pst_completion_str = f'PST is {pst_completed_days/pst_duration_days*100:.2f}% done.'

        # find next 2 important yearly transitions. include time changes, equinoxes, solstices
        year_transitions = [['spring forward', daylight_trans_dates[2]],
                            ['fall back', daylight_trans_dates[3]]]
        year_transitions.append([
            'spring equinox',
            ephem.next_spring_equinox(str(rn.year)).datetime().date()
        ])
        year_transitions.append([
            'summer solstice',
            ephem.next_summer_solstice(str(rn.year)).datetime().date()
        ])
        year_transitions.append([
            'fall equinox',
            ephem.next_fall_equinox(str(rn.year)).datetime().date()
        ])
        year_transitions.append([
            'winter solstice',
            ephem.next_winter_solstice(str(rn.year)).datetime().date()
        ])
        year_transitions.append(['spring forward', daylight_trans_dates[4]])
        year_transitions.append([
            'spring equinox',
            ephem.next_spring_equinox(str(rn.year + 1)).datetime().date()
        ])
        # sort the transitions. (are these astronomical events always guaranteed to be in the same order?)
        year_transitions.sort(key=lambda x: x[1])
        year_transitions = [x for x in year_transitions if rn.date() <= x[1]]
        self.year_transition_1 = f'{year_transitions[0][0]}  {year_transitions[0][1].strftime("%Y.%m.%d")}  ' \
                                 f'Δ{(year_transitions[0][1] - rn.date()).days}d'
        self.year_transition_2 = f'{year_transitions[1][0]}  {year_transitions[1][1].strftime("%Y.%m.%d")}  ' \
                                 f'Δ{(year_transitions[1][1] - rn.date()).days}d'
Esempio n. 11
0
    def __init__(self, latitude: str, longitude: str, timezone: str, year: str,
                 name: str):
        """Take the all necessary location/year/body name information and
        construct plot-ready astronomical body time series for calendar.
        Attributes are all set and ready for queries/plotting after __init__.
        
        Arguments:
        latitude = latitude in decimal degrees as a string, i.e. '36.9577'
        longitude = longitude in decimal degrees as a string, i.e. '-122.0402'
        timezone = tzdata/IANA time zone as a string, i.e. 'America/Los_Angeles'
        year = the year desired for the calendar, as a string, i.e. '2016'
        name = the name of the astronomical body as a string, first letter
               capitalized, i.e. 'Sun' or 'Moon'
        """
        self.latitude = latitude
        self.longitude = longitude
        self.timezone = timezone
        self.year = year
        self.name = name
        
        observer = ephem.Observer()
        observer.lat = ephem.degrees(latitude)
        observer.long = ephem.degrees(longitude)
        observer.elevation = 0
        begin, end = utc_year_bounds(timezone, year)
        step = 10 * ephem.minute #resolution of full timeseries of body heights
        
        alltimes, allheights = fill_in_heights(begin, end, step,
                                             observer, name, append_NaN=False)        
        '''Convert to pandas timeseries and localize the time index.'''
        assert(len(allheights) == len(alltimes))
        hei = pd.Series(allheights, alltimes)
        hei.index = hei.index.tz_localize('UTC')
        hei.index = hei.index.tz_convert(timezone)
        self.altitudes = hei

# ----------------- Special attributes for Sun and Moon ----------------

        '''Equinox and solstice events for Sun'''
        if name == 'Sun':
            spring = ephem.next_spring_equinox(year)
            summer = ephem.next_summer_solstice(year)
            fall = ephem.next_fall_equinox(year)
            winter = ephem.next_winter_solstice(year)
            event_times = [spring.datetime(), summer.datetime(), 
                           fall.datetime(), winter.datetime()]
            event_names = ['spring equinox', 'summer solstice', 'fall equinox',
                           'winter solstice']
            events = pd.Series(event_names, event_times)
            events.index = events.index.tz_localize('UTC')
            events.index = events.index.tz_convert(timezone)
            self.events = events

        '''Daily phase (% illuminated, 28-day icon ID) for Moon'''
        if name == 'Moon':
            moon = ephem.Moon()
            illuminated = []
            observer.date = begin + 22 * ephem.hour  # 10 pm local time Jan 1
            moon.compute(observer)
            while observer.date < end:
                illuminated.append(moon.moon_phase)
                observer.date += 1
                moon.compute(observer)
            daily_times = pd.date_range(year + '-01-01', year + '-12-31', 
                                      tz = timezone)
            assert(len(illuminated) == len(daily_times))
            self.percent_illuminated = pd.Series(illuminated, daily_times)
            
            cycle_days = []            
            moon_day = begin + 22 * ephem.hour   # 10 pm local time Jan 1
            while moon_day < end:
                    cycle_days.append(get_lunation_day(moon_day))
                    moon_day += 1
            assert(len(cycle_days) == len(daily_times))
            self.phase_day_num = pd.Series(cycle_days, daily_times)
            
            exact_names = []
            exact_times = []
            nowdate = begin
            if cycle_days[0] < 14:
                next_full = ephem.next_full_moon(nowdate)
                exact_times.append(next_full.datetime())
                exact_names.append('full')
                nowdate = next_full
            while nowdate < end:
                next_new = ephem.next_new_moon(nowdate)
                exact_times.append(next_new.datetime())
                exact_names.append('new')
                nowdate = next_new
                next_full = ephem.next_full_moon(nowdate)
                exact_times.append(next_full.datetime())
                exact_names.append('full')
                nowdate = next_full
            half_phases = pd.Series(exact_names, exact_times)
            half_phases.index = half_phases.index.tz_localize('UTC')
            half_phases.index = half_phases.index.tz_convert(timezone)
            self.half_phases = half_phases
Esempio n. 12
0
import ephem
year = 1923
while year <= 1924:
    print(year)
    eq1 = ephem.next_spring_equinox(str(year))
    eq3 = ephem.next_autumn_equinox(str(year))
    eq2 = ephem.next_summer_solstice(str(year))
    eq4 = ephem.next_winter_solstice(str(year))
    eq5 = ephem.next_spring_equinox(str(year + 1))
    print("spring equinox: %s" % eq1)
    da = eq1
    while da < eq2:
        fm = ephem.next_full_moon(da)
        if fm > eq2:
            break
        print("  full moon: %s" % fm)
        da = fm
    print("summer solstice: %s" % eq2)
    da = eq2
    while da < eq3:
        fm = ephem.next_full_moon(da)
        if fm > eq3:
            break
        print("  full moon: %s" % fm)
        da = fm
    print("autumn equinox: %s" % eq3)
    while da < eq4:
        fm = ephem.next_full_moon(da)
        if fm > eq4:
            break
        print("  full moon: %s" % fm)