2

I am trying to calculate the azimuth of the rising and setting sun with the following code:

import ephem
import csv
import math

def convert_angle(angle):
    fields = math.modf(angle)
    deg = fields[1]
    min_dec = abs(fields[0]*60)
    min_fields = math.modf(min_dec)
    minu = min_fields[1]
    sec = min_fields[0]*60
    s = '\'{:2.0f}:{:2.0f}:{:2.1f}\''.format(deg,minu,sec)
    return s

sun = ephem.Sun()

with open('locations.txt', 'rb') as csvfile:
    rdrreader = csv.reader(csvfile, delimiter='\t', quotechar='"')
    for row in rdrreader:
        print row[2],row[5],row[6]

        lat = convert_angle(float(row[5]))
        lon = convert_angle(float(row[6]))

        print lat,lon

        obs = ephem.Observer()
        obs.lat = lat       
        obs.lon = lon
        rising = obs.next_rising(sun)
        print('Visual sunrise: %s' % rising)

The script is unhappy with my formatting:

ipdb> c
'60:47:31.2' '-161:52:35.5'
> /Users/mmuratet/weather/solar_ephem.py(35)<module>()
     34         obs = ephem.Observer()
3--> 35         obs.lat = lat       
     36         obs.lon = lon
ipdb> s
ValueError: 'your angle string %r does not have the format     [number[:number[:number]]]'
> /Users/mmuratet/weather/solar_ephem.py(35)<module>()
     34         obs = ephem.Observer()
3--> 35         obs.lat = lat       
     36         obs.lon = lon

and yet the same command works within a python console with cut and paste

>>> obs.lat = '60:47:31.2' 
>>> print obs
<ephem.Observer date='2015/3/3 20:00:58' epoch='2000/1/1 12:00:00'     lon=-161:52:35.5 lat=60:47:31.2 elevation=0.0m horizon=0:00:00.0 temp=15.0C pressure=1010.0mBar>

I know there must be a simple and obvious solution, but I'm not seeing it. Any suggestions will be appreciated.

Here's some data:

AK      Bethel  PABC    60.791987#N     161.876539#W    60.7919870      -161.876539
AK      Fairbanks/Pedro Dome    PAPD    65.0351238#N    147.5014222#W   65.0351238      -147.5014222
user3096277
  • 107
  • 8

1 Answers1

1

It looks like your lat and lon string each have single-quotes inside, one at the beginning of the string and one at the end:

s = '\'{:2.0f}:{:2.0f}:{:2.1f}\''.format(deg,minu,sec)

The single-quotes are not part of the way a scientist would write a latitude or longitude, so PyEphem is confused. Try building the string without the extra two characters inside:

s = '{:2.0f}:{:2.0f}:{:2.1f}'.format(deg,minu,sec)

When it sees only digits and colons, PyEphem should be happy!

Brandon Rhodes
  • 83,755
  • 16
  • 106
  • 147