-
Notifications
You must be signed in to change notification settings - Fork 0
/
moon_phase.py
142 lines (123 loc) · 5.01 KB
/
moon_phase.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
"""
moon_phase.py: a class for determining the current phase of the moon,
and for assigning a weather icon for that phase.
"""
import re
import logging
import datetime
import requests
from bs4 import BeautifulSoup
class MoonPhase(object):
"""
While the length of an average lunar cycle is 29.53 days, to avoid
propagation errors, this class retrieves a table from NOAA that shows the
new moon days and times for the year, and thus the code resets to a known
precise zero each month.
"""
def __init__(self, data=''):
"""
Pull in the date data, mostly.
"""
self.data = data
self.today_v = data['today_vars']
self.baseurl = 'https://tidesandcurrents.noaa.gov/moon_phases.shtml'
self.phases = {
'0': 'wi-moon-alt-new.svg',
'1': 'wi-moon-alt-new.svg',
'2': 'wi-moon-alt-waxing-crescent-1.svg',
'3': 'wi-moon-alt-waxing-crescent-2.svg',
'4': 'wi-moon-alt-waxing-crescent-3.svg',
'5': 'wi-moon-alt-waxing-crescent-4.svg',
'6': 'wi-moon-alt-waxing-crescent-5.svg',
'7': 'wi-moon-alt-waxing-crescent-6.svg',
'8': 'wi-moon-alt-first-quarter.svg',
'9': 'wi-moon-alt-waxing-gibbous-1.svg',
'10': 'wi-moon-alt-waxing-gibbous-2.svg',
'11': 'wi-moon-alt-waxing-gibbous-3.svg',
'12': 'wi-moon-alt-waxing-gibbous-4.svg',
'13': 'wi-moon-alt-waxing-gibbous-5.svg',
'14': 'wi-moon-alt-waxing-gibbous-6.svg',
'15': 'wi-moon-alt-full.svg',
'16': 'wi-moon-alt-waning-gibbous-1.svg',
'17': 'wi-moon-alt-waning-gibbous-2.svg',
'18': 'wi-moon-alt-waning-gibbous-3.svg',
'19': 'wi-moon-alt-waning-gibbous-4.svg',
'20': 'wi-moon-alt-waning-gibbous-5.svg',
'21': 'wi-moon-alt-waning-gibbous-6.svg',
'22': 'wi-moon-alt-third-quarter.svg',
'23': 'wi-moon-alt-waning-crescent-1.svg',
'24': 'wi-moon-alt-waning-crescent-2.svg',
'25': 'wi-moon-alt-waning-crescent-3.svg',
'26': 'wi-moon-alt-waning-crescent-4.svg',
'27': 'wi-moon-alt-waning-crescent-5.svg',
'28': 'wi-moon-alt-waning-crescent-6.svg',
'29': 'wi-moon-alt-new.svg'
}
self.new_moon_dict = dict(year={})
def get_moon_phase(self):
"""
run methods in the correct order.
"""
self.retrieve_new_moon_dict()
svg_name = self.moon_phase_today()
return svg_name
def bs_pull_table_cell(self, row, index):
"""
Helper function to sanitize and pull a specific cell from a specific table
row.
"""
try:
return re.sub('\xa0', '', row.find_all('td')[index].text)
except IndexError as exc:
logging.error('IndexError trying to retrieve table cell %s: %s', index, exc)
logging.error('Row: %s', row)
return 'NA'
def retrieve_new_moon_dict(self):
"""
Using some simple math, compute the moon phase for today, using
NOAA's data for new moons in the current year.
"""
thisyear = self.today_v['year']
self.new_moon_dict['year'][thisyear] = {}
url_args = {'year': thisyear, 'data_type': 'phaX1'}
logging.debug('Retrieving moon phase data from %s', self.baseurl)
moon_table = requests.get(self.baseurl, params=url_args,
verify=True, timeout=10)
if moon_table.status_code != 200:
logging.error('Unable to get a proper response from NOAA server. Returning False.')
return False
logging.debug('Parsing the new moon html table from NOAA.')
soup = BeautifulSoup(moon_table.text, 'html.parser')
tables = soup.body.find_all('table')
phase_table = tables[0]
trows = phase_table.find_all('tr')
for row in trows:
if row.find_all('th'):
continue
rowmonth = self.bs_pull_table_cell(row, 1)
rowday = self.bs_pull_table_cell(row, 2)
rowtime = self.bs_pull_table_cell(row, 3)
self.new_moon_dict['year'][thisyear][rowmonth] = [rowday, rowtime]
return self.new_moon_dict
def moon_phase_today(self):
"""
Take in a date and determine the moon's phase on that day, using
NOAA new moon dates and times as the time-base / sync.
"""
today = self.today_v['utcnow']
year = self.today_v['year']
mon = self.today_v['mon']
nextmoonstring = '{0}-{1}-{2} {3}'.format(year, mon,
self.new_moon_dict['year'][year][mon][0],
self.new_moon_dict['year'][year][mon][1])
nextnewmoon = datetime.datetime.strptime(nextmoonstring, '%Y-%b-%d %H:%M')
difference = nextnewmoon - today
cycle = 29.53 # days in an average moon cycle
place_in_cycle = (datetime.timedelta(cycle) - difference)
days_into_cycle = ((place_in_cycle.days * 24) + (place_in_cycle.seconds/3600.0)) / 24
while days_into_cycle > cycle:
days_into_cycle = days_into_cycle - cycle
logging.info('Place in the lunar cycle: %s', days_into_cycle)
icon_index = int((days_into_cycle / cycle) * 29)
logging.info('Icon should be: %s', self.phases[str(icon_index)])
return self.phases[str(icon_index)]