Where is the Sun?
Jordan S. Ford

Solar-powered robots live and die by the sun, but finding it isn't always easy. JPL tracks and publishes the positions and orientations of the sun, the planets, and their moons, but the JPL file formats are poorly documented for outsiders, and the maze of coordinates and timescales is intimidating. Fortunately, there's Skyfield, an amazing python3 library for astronomy. Brandon Rhodes, the author of Skyfield, has helped me find the relative angle to the sun from any location on Earth or the Moon, and I'm publishing the code here in case it helps someone like me in the future.

  
  from skyfield.api import PlanetaryConstants, load

  def sun_from_moon(pos, time_utc):
    eph = load('de421.bsp')
    sun = eph['sun']
    moon = eph['moon']

    pc = PlanetaryConstants()
    pc.read_text(load('moon_080317.tf'))
    pc.read_text(load('pck00008.tpc'))
    pc.read_binary(load('moon_pa_de421_1900-2050.bpc'))
    frame = pc.build_frame_named('MOON_ME_DE421')

    place = moon + pc.build_latlon_degrees(frame, pos[0], pos[1])
    sunpos = place.at(time_utc).observe(sun).apparent()
    alt, az, distance = sunpos.altaz()
    return (alt.degrees, az.degrees)

  def sun_from_earth(pos, time_utc):
    eph = load('de421.bsp')
    sun = eph['sun']
    earth = eph['earth']

    place = earth + wgs84.latlon(time_utc[0], time_utc[1])
    sunpos = place.at(time_utc).observe(sun).apparent()
    alt, az, distance = sunpos.altaz()
    return (alt.degrees, az.degrees)

  if __name__ == "__main__":
    ts = load.timescale()
    t = ts.utc(2020, 4, 23)

    # Where is the sun from Mare Tranquilitatis?
    lat, lon = sun_from_moon((8.5, 31.4), t)
    print(lat, lon)

    # Where is the sun from Pittsburgh?
    lat, lon = sun_from_earth((40.4406, -79.9959), t)
    print(lat, lon)