How to calculate the angle of the sun above the horizon using pyEphem
Asked Answered
I

1

7

I'm new to PyEphem and this is probably a simple question. I want to calculate the angle of the sun above the horizon at a certain GPS point and date. My code is as follows:

import ephem
import datetime

date = datetime.datetime(2010,1,1,12,0,0)
print "Date: " + str(date)

obs=ephem.Observer()
obs.lat='31:00'
obs.long='-106:00'
obs.date = date
print obs

sun = ephem.Sun(obs)
sun.compute(obs)
print float(sun.alt)
print str(sun.alt)
sun_angle = float(sun.alt) * 57.2957795 # Convert Radians to degrees
print "sun_angle: %f" % sun_angle

And the output is:

python sunTry.py
Date: 2010-01-01 12:00:00
<ephem.Observer date='2010/1/1 12:00:00' epoch='2000/1/1 12:00:00' lon=-106:00:00.0 lat=31:00:00.0 elevation=0.0m horizon=0:00:00.0 temp=15.0C pressure=1010.0mBar>
-0.44488877058
-25:29:24.9
sun_angle: -25.490249

Why is the alt negative? The GPS location is somewhere in Mexico and I've specified 12 Noon in the date parameter of the observer. The sun should be pretty much directly overhead so I would have thought that the alt variable would return an angle somewhere int he range of 70 - 90 degrees? What am I missing here?

Thanks

Stephen

Ideomotor answered 9/8, 2013 at 23:48 Comment(1)
My memory is a little fuzzy with datetime usage. Is it possible that there is a time zone issue there? Maybe ephem and datetime are conspiring to interpret your time as in some other time zone, such as UTC or your local TZ?Writer
M
4

I believe the problem is that in PyEphem, dates are always in UTC. So no matter what the local timezone is for your observer's lat/lon, if you tell it Noon, it assumes you mean Noon in UTC. That means you have to pass in the time you intend already converted to UTC.

The UTC time for "somewhere in Mexico at datetime.datetime(2010,1,1,12,0,0)" is roughly datetime.datetime(2010,1,1,18,0,0).

With this new date, I get the output

sun_angle: 33.672932

That still seems kind of low, but more reasonable than -25.

If you want a programmatic way of doing it, you can (at your own risk) meddle with the module pytz.

tz_mexico = pytz.timezone('America/Mexico_City')
mexico_time = datetime.datetime(2010,1,1,12,0,0,0,tz_mexico)
utc_time = mexico_time.astimezone(pytz.utc)
obs.date = utc_time
Maryland answered 10/8, 2013 at 0:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.