Python PyEphem – Calculate the position of Mars

In this post we will be creating a Python script that will calculate the position of planet Mars in the sky for a given date and location, to achieve this we will be using the PyEphem library which is able to perform high-precision astronomy computations.

To install the PyEphem library run the following command.

``pip install ephem``

Our example will take the latitude and longitude coordinates of a given observer location. In this case our location will be the Big Ben tower in London, the coordinates for which are.

``````'51.5007'  #latitude of Big Ben (degrees)
'-0.1246'  #longitude of Big Ben (degrees)``````

See the snippet of Python code below where we utilize the PyEphem library to calculate the position of the planet Mars in the sky for a given date and location.

We begin by setting up an observer object for the Big Ben tower, defining its latitude and longitude coordinates. We then create an object for Mars and calculate its position in the sky.

The position of Mars is returned as an altitude and azimuth.

``````import ephem

obs = ephem.Observer()
obs.lat = '51.5007'
obs.lon = '-0.1246'
obs.elevation = 0
obs.date = '2023/1/30 17:00:00'

mars = ephem.Mars(obs)

mars.compute(obs)

print("Azimuth:", mars.az)
print("Altitude:", mars.alt)``````

At the time of writing this the following is returned to output.

``````Azimuth: 112:24:06.1
Altitude: 47:31:56.7
>>> ``````

Take a look at some of our other content around the Python programming language by clicking here.