public
Last active

Phase of the moon

  • Download Gist
moonphase.py
Python
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
#!/usr/bin/env python
# http://en.wikipedia.org/wiki/Lunar_phase#Calculating_phase
 
import math, decimal, datetime
dec = decimal.Decimal
 
def position(now=None):
if now is None:
now = datetime.datetime.now()
 
diff = now - datetime.datetime(2011, 11, 25, 6, 9, 35)
days = dec(diff.days) + (dec(diff.seconds) / dec(86400))
lunations = days % dec("29.530588853")
 
return lunations
 
def phase(pos):
sixteenth = dec("29.530588853") / dec(16)
if pos < sixteenth:
return "New Moon"
elif pos < sixteenth * 3:
return "Waxing Crescent"
elif pos < sixteenth * 5:
return "First Quarter"
elif pos < sixteenth * 7:
return "Waxing Gibbous"
elif pos < sixteenth * 9:
return "Full Moon"
elif pos < sixteenth * 11:
return "Waning Gibbous"
elif pos < sixteenth * 13:
return "Last Quarter"
elif pos < sixteenth * 15:
return "Waning Crescent"
else: return "New Moon"
 
def main():
pos = position()
phasename = phase(pos)
 
roundedpos = round(float(pos / dec("29.530588853")), 3)
print "%s (%s)" % (phasename, roundedpos)
 
if __name__=="__main__":
main()

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.