### Install Pandas Source: https://github.com/skyfielders/python-skyfield/blob/master/documentation/kepler-orbits.rst Install the Pandas library, which is required for loading orbital elements from text files. ```bash pip install pandas ``` -------------------------------- ### Install Skyfield Source: https://github.com/skyfielders/python-skyfield/blob/master/README.rst Install Skyfield using pip. This command assumes NumPy is already installed or will be installed as a dependency. ```bash pip install skyfield ``` -------------------------------- ### Version Information Source: https://github.com/skyfielders/python-skyfield/blob/master/documentation/api.rst Access the installed version of Skyfield using the VERSION constant. ```APIDOC ## Version Information Access the installed version of Skyfield using the `skyfield.VERSION` tuple. ### Usage ```python import skyfield print(skyfield.VERSION) ``` ``` -------------------------------- ### Get Skyfield Version Source: https://github.com/skyfielders/python-skyfield/blob/master/documentation/api.rst Check the installed version of the Skyfield library. ```python import skyfield print(skyfield.VERSION) ``` -------------------------------- ### Load Multiple Ephemeris Files and Observe Source: https://github.com/skyfielders/python-skyfield/blob/master/documentation/planets.rst Load multiple ephemeris files to access data from different sources. This example demonstrates loading 'jup310.bsp' and attempting an observation that fails due to missing data (Saturn). ```python jup310 = load('jup310.bsp') ganymede = jup310['Ganymede'] a = ganymede.at(t).observe(earth).apparent() ``` -------------------------------- ### Extract Minor Planet Orbits (Linux) Source: https://github.com/skyfielders/python-skyfield/blob/master/documentation/kepler-orbits.rst Example of extracting specific minor planet orbits from a gzipped MPCORB.DAT file on a Linux system using zgrep. ```bash zgrep -P '^(00001|00002|00003|00004) ' MPCORB.DAT.gz > MPCORB.excerpt.DAT ``` -------------------------------- ### Create a Timescale Object Source: https://github.com/skyfielders/python-skyfield/blob/master/documentation/api.rst Initialize a Skyfield `Timescale` object, which is typically done once at the start of a script for all date and time conversions. ```python from skyfield import api ts = api.load.timescale() ``` -------------------------------- ### Compare Distances from Earth's Center for Different Locations Source: https://github.com/skyfielders/python-skyfield/blob/master/documentation/examples.rst This example calculates and compares the distance from the Earth's center to two different geographic locations, considering both latitude and elevation. It demonstrates how the Earth's equatorial bulge can make locations near the equator farther from the center than higher-elevation locations at other latitudes. ```python from skyfield.api import N, W, wgs84, load from skyfield.functions import length_of ts = load.timescale() t = ts.utc(2019, 1, 1) bierstadt = wgs84.latlon(39.5828 * N, 105.6686 * W, elevation_m=4287.012) m1 = length_of(bierstadt.at(t).xyz.m) print(int(m1)) accra = wgs84.latlon(5.6037 * N, 0.1870 * W, elevation_m=61) m2 = length_of(accra.at(t).xyz.m) print(int(m2)) assert m2 > m1 print("I was", int(m2 - m1), "meters farther from the Earth's center\n" ``` -------------------------------- ### Calculate Separation and Ecliptic Coordinates at Opposition Source: https://github.com/skyfielders/python-skyfield/blob/master/documentation/examples.rst Demonstrates calculating the angular separation and ecliptic coordinates for the Sun and Mars during opposition. This example shows how orbital inclination affects apparent separation. ```python t = ts.utc(2020, 10, 13, 23, 25, 55) e = earth.at(t) s = e.observe(sun).apparent() m = e.observe(mars).apparent() print('Separation: {:.5f}°'.format(m.separation_from(s).degrees)) print('') print(' Latitude Longitude') lat, lon, distance = s.frame_latlon(ecliptic_frame) print('Sun {:.5f}° {:.5f}°'.format(lat.degrees, lon.degrees)) lat, lon, distance = m.frame_latlon(ecliptic_frame) print('Mars {:.5f}° {:.5f}°'.format(lat.degrees, lon.degrees)) ``` -------------------------------- ### Create a Timescale Object Source: https://context7.com/skyfielders/python-skyfield/llms.txt The Timescale object is essential for converting between various astronomical time scales (UTC, TAI, TT, TDB, UT1). It automatically downloads leap-second data if needed. This example demonstrates creating a timescale and converting moments into different formats. ```python from skyfield.api import Loader load = Loader('~/skyfield-data') ts = load.timescale() # downloads finals2000A.all if needed # Various ways to express the same moment. t_utc = ts.utc(2024, 6, 21, 12, 0, 0) t_tt = ts.tt(2024, 6, 21, 12, 0, 37.184) # TT ≈ UTC + 69.184 s in 2024 t_now = ts.now() print(t_utc.utc_iso()) # 2024-06-21T12:00:00Z print(t_utc.tt) # Julian date in Terrestrial Time print(t_utc.ut1_fraction) # UT1 fractional Julian day ``` -------------------------------- ### Initialize Satrec with Orbital Parameters Source: https://github.com/skyfielders/python-skyfield/blob/master/documentation/earth-satellites.rst Manually initialize a `Satrec` object with detailed orbital parameters for a satellite. This is useful when you have raw orbital data instead of TLE lines. ```python from sgp4.api import Satrec, WGS72 satrec = Satrec() satrec.sgp4init( WGS72, # gravity model 'i', # 'a' = old AFSPC mode, 'i' = improved mode 5, # satnum: Satellite number 18441.785, # epoch: days since 1949 December 31 00:00 UT 2.8098e-05, # bstar: drag coefficient (/earth radii) 6.969196665e-13, # ndot: ballistic coefficient (radians/minute^2) 0.0, # nddot: second derivative of mean motion (radians/minute^3) 0.1859667, # ecco: eccentricity 5.7904160274885, # argpo: argument of perigee (radians) 0.5980929187319, # inclo: inclination (radians) 0.3373093125574, # mo: mean anomaly (radians) 0.0472294454407, # no_kozai: mean motion (radians/minute) 6.0863854713832, # nodeo: right ascension of ascending node (radians) ) ``` -------------------------------- ### Display Skyfield version from command line Source: https://github.com/skyfielders/python-skyfield/blob/master/documentation/installation.rst Invoke the skyfield module directly from the command line to display its version and the versions of its dependencies. ```bash $ python -m skyfield ``` -------------------------------- ### Load Hipparcos Catalog Dataframe Source: https://github.com/skyfielders/python-skyfield/blob/master/documentation/stars.rst Loads the Hipparcos star catalog into a Pandas dataframe. Requires the Pandas library to be installed. ```python from skyfield.api import Star, load from skyfield.data import hipparcos with load.open(hipparcos.URL) as f: df = hipparcos.load_dataframe(f) ``` -------------------------------- ### Build and Print UTC Times Source: https://github.com/skyfielders/python-skyfield/blob/master/documentation/time.rst Demonstrates four equivalent ways to specify the same UTC date and time, and shows various methods for printing the time in UTC format. Access individual components like year, month, day, hour, minute, and second. ```python t1 = ts.utc(2014, 1, 18.06640625) t2 = ts.utc(2014, 1, 18, 1.59375) t3 = ts.utc(2014, 1, 18, 1, 35.625) t4 = ts.utc(2014, 1, 18, 1, 35, 37.5) assert t1 == t2 == t3 == t4 print(tuple(t1.utc)) print(t1.utc_iso()) print(t1.utc_strftime()) print(t1.utc_strftime('On %Y %b %d at %H:%M:%S')) print(t1.utc_jpl()) ``` ```python print(t1.utc.year, '/', t1.utc.month, '/', t1.utc.day) print(t1.utc.hour, ':', t1.utc.minute, ':', t1.utc.second) ``` -------------------------------- ### Get Satellite Latitude and Longitude Source: https://github.com/skyfielders/python-skyfield/blob/master/documentation/earth-satellites.rst Obtain the latitude and longitude of a satellite from its geocentric position using the WGS84 ellipsoid model. ```python lat, lon = wgs84.latlon_of(geocentric) print('Latitude:', lat) print('Longitude:', lon) ``` -------------------------------- ### Initialize SpiceKernel with Unsupported Data Type Source: https://github.com/skyfielders/python-skyfield/blob/master/documentation/planets.rst Attempt to initialize a SpiceKernel with an ephemeris file that uses an unsupported SPK data type (e.g., type 21). This will raise a ValueError. ```python from skyfield.jpllib import SpiceKernel kernel = SpiceKernel('wld23593.15') ``` -------------------------------- ### Load an ephemeris file at runtime Source: https://github.com/skyfielders/python-skyfield/blob/master/CHANGELOG.rst Ask for a SPICE ephemeris to be downloaded at runtime with a call to load. This removes the ephemeris as an install-time dependency. ```python planets = load('de421.bsp') ``` -------------------------------- ### Get Periapsis Time and Period Source: https://github.com/skyfielders/python-skyfield/blob/master/documentation/elements.rst Access the `periapsis_time` and `period_in_days` attributes from the `OsculatingElements` object. The periapsis time is a `Time` object, and the period is in days. ```python print('Periapsis:', elements.periapsis_time.utc_strftime()) print('Period: {0:.2f} days'.format(elements.period_in_days)) ``` -------------------------------- ### Create and Print Time Scales Source: https://github.com/skyfielders/python-skyfield/blob/master/documentation/time.rst Demonstrates creating a timescale object and printing a moment in different time scales (TT, TAI, UTC) and Julian dates (TDB, J). ```python from skyfield.api import load ts = load.timescale() t = ts.tt(2000, 1, 1, 12, 0) print('TT date and time: ', t.tt_strftime()) print('TAI date and time:', t.tai_strftime()) print('UTC date and time:', t.utc_strftime()) print('TDB Julian date: {:.10f}'.format(t.tdb)) print('Julian century: {:.1f}'.format(t.J)) ``` -------------------------------- ### Get Satellite Epoch Source: https://github.com/skyfielders/python-skyfield/blob/master/documentation/earth-satellites.rst Retrieves the epoch (date of maximum accuracy) of a satellite's TLE data. The epoch is returned as a Skyfield Time object. ```python print(satellite.epoch.utc_jpl()) ``` -------------------------------- ### Get Current Moon Phase Source: https://github.com/skyfielders/python-skyfield/blob/master/documentation/almanac.rst Calculate the current phase of the Moon. The result is an angle in degrees, where 0° is New Moon and 180° is Full Moon. ```python t = ts.utc(2020, 11, 19) phase = almanac.moon_phase(eph, t) print('Moon phase: {:.1f} degrees'.format(phase.degrees)) ``` -------------------------------- ### Create a custom loader object Source: https://github.com/skyfielders/python-skyfield/blob/master/CHANGELOG.rst Instantiate a custom loader to specify a target directory for downloaded ephemeris files. This replaces the need for special keyword arguments on every download. ```python load = api.Loader('~/ephemeris-files') load('de421.bsp') ``` -------------------------------- ### Generate Osculating Elements for Moon Orbiting Earth Source: https://github.com/skyfielders/python-skyfield/blob/master/documentation/elements.rst Use `osculating_elements_of` to get orbital elements. This requires a timescale, time, and planetary ephemeris data. ```python from skyfield.api import load from skyfield.elementslib import osculating_elements_of ts = load.timescale() t = ts.utc(2018, 4, 22) planets = load('de421.bsp') earth = planets['earth'] moon = planets['moon'] position = (moon - earth).at(t) elements = osculating_elements_of(position) ``` -------------------------------- ### Create Star with Proper Motion and Parallax Source: https://github.com/skyfielders/python-skyfield/blob/master/documentation/stars.rst Initializes a Star object including proper motion (mas/year), parallax (mas), and radial velocity (km/s) to calculate its true position and distance. ```python barnard = Star(ra_hours=(17, 57, 48.49803), dec_degrees=(4, 41, 36.2072), ra_mas_per_year=-798.71, dec_mas_per_year=+10337.77, parallax_mas=545.4, radial_km_per_s=-110.6) astrometric = earth.at(t).observe(barnard) ra, dec, distance = astrometric.radec() print(ra) print(dec) print(distance) ``` -------------------------------- ### risings_and_settings Source: https://github.com/skyfielders/python-skyfield/blob/master/documentation/api-almanac.rst Calculates the times of risings and settings. ```APIDOC ## risings_and_settings ### Description Calculates the times of risings and settings. ### Parameters (Details not provided in source) ``` -------------------------------- ### Get Satellite Right Ascension and Declination Source: https://github.com/skyfielders/python-skyfield/blob/master/documentation/earth-satellites.rst Retrieves the right ascension and declination of a satellite relative to the ICRF (J2000) or the dynamical coordinate system of a specified date. ```python ra, dec, distance = topocentric.radec() # ICRF ("J2000") print(ra) print(dec) ``` ```python ra, dec, distance = topocentric.radec(epoch='date') print(ra) print(dec) ``` -------------------------------- ### Get Satellite Altitude and Azimuth Source: https://github.com/skyfielders/python-skyfield/blob/master/documentation/earth-satellites.rst Determine the satellite's altitude (angle above horizon) and azimuth (direction) from an observer's perspective. Checks if the satellite is above the horizon. ```python alt, az, distance = topocentric.altaz() if alt.degrees > 0: print('The ISS is above the horizon') ``` -------------------------------- ### Ask for planet positions with body.at(t) Source: https://github.com/skyfielders/python-skyfield/blob/master/CHANGELOG.rst Use the body.at(t) method to ask for planet positions, which replaces the older body(t) syntax. ```python body.at(t) ``` -------------------------------- ### Get Coordinates from a Position Object Source: https://github.com/skyfielders/python-skyfield/blob/master/documentation/design.rst Shows how to retrieve different coordinate systems (like Radec, ecliptic, or galactic) from a position object using method calls. ```python astrometric.radec() ``` ```python astrometric.ecliptic_latlon() ``` ```python astrometric.galactic_latlon() ``` -------------------------------- ### Vector Scaling with NumPy Reshape Source: https://github.com/skyfielders/python-skyfield/blob/master/documentation/design.rst Illustrates how to scale a 3D vector by a scalar and by a 1D array using NumPy, demonstrating the effect of reshape. ```python from numpy import array, cross, matrix, float64 m = array([4.0,5.0,6.0]) arg1 = float64(2.0) argn = array([2.0, 3.0]) # Scale by a scalar arg1 * m.reshape(3,) # Scale by a 1D array (broadcasts to a 2D array) argn * m.reshape(3, 1) ``` -------------------------------- ### Calculate Refraction and Find Risings/Settings Source: https://github.com/skyfielders/python-skyfield/blob/master/documentation/almanac.rst Calculates atmospheric refraction and uses it to find the precise times of celestial body risings and settings. Requires importing the refraction function and providing temperature and pressure. ```python from skyfield.earthlib import refraction r = refraction(0.0, temperature_C=15.0, pressure_mbar=1030.0) print('Refraction at the horizon: %.2f arcminutes\n' % (r * 60.0)) t, y = almanac.find_risings(observer, eph['Mars'], t0, t1, horizon_degrees=-r) print('Mars rises:', t.utc_iso(' ')) t, y = almanac.find_settings(observer, eph['Mars'], t0, t1, horizon_degrees=-r) print('Mars sets: ', t.utc_iso(' ')) ``` -------------------------------- ### Get Satellite Epoch Time Source: https://github.com/skyfielders/python-skyfield/blob/master/documentation/earth-satellites.rst Retrieve the epoch date and time from a satellite's TLE data. The epoch indicates when the TLE element set's predictions are most accurate. ```python from skyfield.api import EarthSatellite text = """ GOCE 1 34602U 09013A 13314.96046236 .14220718 20669-5 50412-4 0 930 2 34602 096.5717 344.5256 0009826 296.2811 064.0942 16.58673376272979 """ lines = text.strip().splitlines() sat = EarthSatellite(lines[1], lines[2], lines[0]) print(sat.epoch.utc_jpl()) ``` -------------------------------- ### Create Apparent Position from RA and Dec Source: https://github.com/skyfielders/python-skyfield/blob/master/documentation/coordinates.rst Creates an apparent position object from right ascension and declination values. Useful when starting with celestial coordinates rather than observing a body. ```python from skyfield.positionlib import Apparent position = Apparent.from_radec(ra_hours=5.59, dec_degrees=5.45) ``` -------------------------------- ### PlanetaryConstants Source: https://context7.com/skyfielders/python-skyfield/llms.txt Loads NAIF SPICE PCK (planetary constants) and FK (frame kernel) files to enable computing surface coordinates, sub-observer points, and positions in body-fixed frames for planets and their moons. ```APIDOC ## `PlanetaryConstants` / SPICE kernels — planetary body frames Loads NAIF SPICE PCK (planetary constants) and FK (frame kernel) files to enable computing surface coordinates, sub-observer points, and positions in body-fixed frames for planets and their moons. ```python from skyfield.api import load, PlanetaryConstants ts = load.timescale() planets = load('de421.bsp') earth = planets['earth'] pc = PlanetaryConstants() pc.read_text(load.open('pck00008.tpc')) # rotation/shape constants pc.read_text(load.open('moon_080317.tf')) # Moon frame kernel pc.read_binary(load.open('moon_pa_de421_1900-2050.bpc')) # Moon orientation moon_frame = pc.build_frame_named('MOON_ME') moon = planets['moon'] t = ts.utc(2025, 7, 20, 20, 17, 40) # Apollo 11 anniversary apparent = earth.at(t).observe(moon).apparent() lat, lon, _ = apparent.frame_latlon(moon_frame) print(f'Sub-Earth point: {lat}, {lon}') ``` ``` -------------------------------- ### Observe from a Moon Location Source: https://github.com/skyfielders/python-skyfield/blob/master/documentation/planetary.rst Determine where an astronaut on the Moon would see a celestial body. Provides coordinates in RA/Dec and altitude/azimuth. Requires similar setup to observing a Moon location. ```python from skyfield.api import PlanetaryConstants, load ts = load.timescale() t = ts.utc(2019, 12, 20, 11, 5) eph = load('de421.bsp') earth, moon = eph['earth'], 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') aristarchus = moon + pc.build_latlon_degrees(frame, 26.3, -46.8) apparent = aristarchus.at(t).observe(earth).apparent() ra, dec, distance = apparent.radec(epoch='date') print(ra) print(dec) alt, az, distance = apparent.altaz() print(alt, 'degrees above the horizon') print(az, 'degrees around the horizon from north') ``` -------------------------------- ### Find Risings and Settings of a Celestial Object Source: https://github.com/skyfielders/python-skyfield/blob/master/documentation/examples.rst Calculates and prints the rising and setting times for a celestial object from a specific location. Requires Skyfield, pytz, and an ephemeris file. ```python from skyfield.api import N, Star, W, wgs84, load from skyfield.almanac import find_discrete, risings_and_settings from pytz import timezone ts = load.timescale() t0 = ts.utc(2019, 1, 19) t1 = ts.utc(2019, 1, 21) moab = wgs84.latlon(38.5725 * N, 109.54972238 * W) eph = load('de421.bsp') gc = Star(ra_hours=(17, 45, 40.04), dec_degrees=(-29, 0, 28.1)) f = risings_and_settings(eph, gc, moab) tz = timezone('US/Mountain') for t, updown in zip(*find_discrete(t0, t1, f)): print(t.astimezone(tz).strftime('%a %d %H:%M'), 'MST', 'rises' if updown else 'sets') ``` -------------------------------- ### Get Mars Astrometric RA and Dec Source: https://github.com/skyfielders/python-skyfield/blob/master/documentation/searches.rst Retrieves the Right Ascension (RA) and Declination (Dec) for Mars using astrometric positions. This is useful for detailed comparison with external astronomical data. ```python ra, dec, distance = m.radec() print(ra, '/', dec) ``` -------------------------------- ### Load and Download Ephemeris File Source: https://github.com/skyfielders/python-skyfield/blob/master/documentation/api.rst Load an ephemeris file, downloading it automatically if it does not exist. ```python # File you want Skyfield to download automatically. from skyfield.api import load ts = load.timescale() planets = load('de405.bsp') ``` -------------------------------- ### Spherical and Cartesian Coordinates (True Equator) Source: https://github.com/skyfielders/python-skyfield/blob/master/documentation/coordinates.rst Import and use the `true_equator_and_equinox_of_date` frame to get spherical (RA/Dec) and Cartesian (x,y,z) coordinates. Set RA preference to 'hours' for display. ```python from skyfield.framelib import true_equator_and_equinox_of_date print('Spherical equinox-of-date coordinates:') dec, ra, distance = position.frame_latlon(true_equator_and_equinox_of_date) ra.preference = 'hours' # print hours instead of degrees print(' ', ra, 'right ascension') print(' ', dec, 'declination') print(' ', distance, 'distance') print() print('Cartesian equinox-of-date coordinates:') x, y, z = position.frame_xyz(true_equator_and_equinox_of_date).au print(' x = {:.6f} au'.format(x)) print(' y = {:.6f} au'.format(y)) print(' z = {:.6f} au'.format(z)) ``` -------------------------------- ### Load MPCORB Data into Pandas DataFrame Source: https://context7.com/skyfielders/python-skyfield/llms.txt Loads the Minor Planet Center MPCORB catalog into a Pandas DataFrame for asteroid orbital elements. Requires the 'de421.bsp' ephemeris and 'MPCORB_URL' data file. ```python from skyfield.api import load from skyfield.data import mpc from skyfield.constants import GM_SUN_Pitjeva_2005_km3_s2 as GM_SUN ts = load.timescale() with load.open(mpc.MPCORB_URL) as f: minor_planets = mpc.load_mpcorb_dataframe(f) # Filter to the first 10 numbered asteroids. sample = minor_planets.iloc[:10] planets = load('de421.bsp') sun = planets['sun'] earth = planets['earth'] t = ts.utc(2025, 6, 1) for _, row in sample.iterrows(): orbit = mpc.mpcorb_orbit(row, ts, GM_SUN) astrometric = earth.at(t).observe(sun + orbit) ra, dec, distance = astrometric.radec() print(f'{row["designation"]:20s} RA={ra} Dec={dec} dist={distance}') ``` -------------------------------- ### Date arithmetic operations Source: https://github.com/skyfielders/python-skyfield/blob/master/documentation/time.rst Demonstrates basic date arithmetic in Skyfield, including subtracting days, adding fractions of days (which are converted to hours), and adding timedelta objects. It also shows how to calculate the difference between two times. ```python from datetime import timedelta t - 10 # 10 days earlier t + 0.25 # 6 hours later t + timedelta(hours=12) # 12 hours later t2 - t1 # difference between times, in days ``` -------------------------------- ### Calculate Moon's Distance Moved Source: https://github.com/skyfielders/python-skyfield/blob/master/documentation/positions.rst Calculate the distance the Moon moved in kilometers over a specific time interval. This snippet requires prior setup of time and celestial body objects. ```python moon = planets['moon'] p1 = moon.at(t1) p2 = moon.at(t2) km = (p2 - p1).distance().km print('In one minute the Moon moved %d km' % km) ``` -------------------------------- ### Create Time Arrays Using Range Source: https://github.com/skyfielders/python-skyfield/blob/master/documentation/time.rst Demonstrates creating time arrays by providing a range for one of the calendar components (year, month, day, hour, minute, or second). This method is flexible for varying specific time units while keeping others constant. ```python ts.utc(range(1900, 1950)) ``` ```python ts.utc(1980, range(1, 25)) ``` ```python ts.utc(2005, 5, [1, 11, 21]) ``` ```python ts.utc(1975, 1, 1, 0, 0, range(-5, 5)) ``` -------------------------------- ### Calculate Legacy Risings and Settings for Planets Source: https://github.com/skyfielders/python-skyfield/blob/master/documentation/almanac.rst Determines the times when a celestial body, like Mars, rises and sets using a legacy routine. The output 'y' indicates rising (1) or setting (0). ```python f = almanac.risings_and_settings(eph, eph['Mars'], bluffton) t, y = almanac.find_discrete(t0, t1, f) print(t.utc_iso()) print(y) ``` -------------------------------- ### Calculate Satellite Range Rate Source: https://github.com/skyfielders/python-skyfield/blob/master/documentation/earth-satellites.rst Determines the rate at which a satellite's range to an antenna is changing, useful for Doppler shift calculations. This example calculates range and range rate over a series of times. ```python t = ts.utc(2014, 1, 23, 11, range(17, 23)) pos = (satellite - bluffton).at(t) _, _, the_range, _, _, range_rate = pos.frame_latlon_and_rates(bluffton) from numpy import array2string print(array2string(the_range.km, precision=1), 'km') print(array2string(range_rate.km_per_s, precision=2), 'km/s') ``` -------------------------------- ### Measure Polar Motion Excursions Source: https://github.com/skyfielders/python-skyfield/blob/master/documentation/accuracy-efficiency.rst Load IERS data to measure the maximum excursions of Earth's polar motion parameters x and y. This requires installing the polar motion table on the timescale object. ```python from skyfield.api import load from skyfield.data import iers url = load.build_url('finals2000A.all') with load.open(url) as f: finals_data = iers.parse_x_y_dut1_from_finals_all(f) ts = load.timescale() iers.install_polar_motion_table(ts, finals_data) t, x_arcseconds, y_arcseconds = ts.polar_motion_table print('x:', max(abs(x_arcseconds)), 'arcseconds') print('y:', max(abs(y_arcseconds)), 'arcseconds') ``` -------------------------------- ### Specify download directory for ephemeris files Source: https://github.com/skyfielders/python-skyfield/blob/master/CHANGELOG.rst Provide a target directory when downloading a file using the load function. This allows users to manage where ephemeris files are stored. ```python load('de421.bsp', directory='~/ephemerides') ``` -------------------------------- ### Get Current UTC Time Source: https://github.com/skyfielders/python-skyfield/blob/master/documentation/time.rst Obtain the current date and time as a Skyfield Time object by leveraging the system clock. Assumes the operating system clock is accurate and correctly configured with the time zone. ```python from skyfield.api import load ts = load.timescale() t = ts.now() print(t.utc_jpl()) ``` -------------------------------- ### Push Development Branch Source: https://github.com/skyfielders/python-skyfield/blob/master/Contrib.rst Push your new development branch to your GitHub fork. ```bash git push origin fix42 ``` -------------------------------- ### Apply Aberration and Deflection Corrections for Apparent Position Source: https://context7.com/skyfielders/python-skyfield/llms.txt Chain `.apparent()` onto `.observe()` to get an apparent position that includes corrections for stellar aberration and gravitational light deflection. This matches almanac coordinates. ```python from skyfield.api import load ts = load.timescale() planets = load('de421.bsp') earth = planets['earth'] mars = planets['mars'] t = ts.utc(2025, 8, 12, 6, 0, 0) apparent = earth.at(t).observe(mars).apparent() ra, dec, distance = apparent.radec(epoch='date') # epoch-of-date frame print(ra) # RA in the true equator/equinox of 2025-08-12 print(dec) ``` -------------------------------- ### Find Sunsets using Skyfield Source: https://github.com/skyfielders/python-skyfield/blob/master/documentation/almanac.rst Compute sunset times for a given observer and celestial body between a start and end time. The `find_settings` function returns the times and a boolean array indicating if a setting was detected. ```python t, y = almanac.find_settings(observer, sun, t0, t1) print(t.utc_iso(' ')) print(y) ``` -------------------------------- ### Download Satellite Elements with Skyfield Source: https://github.com/skyfielders/python-skyfield/blob/master/documentation/earth-satellites.rst This pattern demonstrates how to download satellite element sets using Skyfield. It includes advice on saving data to a file to reduce server load and how to use the `filename=` argument to prevent overwriting data from different sources. ```python from skyfield.api import load ts = load.timescale() # Download the 'stations' element set and save it to 'stations.tle' satellites = load.tle_file('stations.tle', filename='gp.php?GROUP=stations', reload=True) # Download the 'cubesat' element set and save it to 'cubesat.tle' satellites = load.tle_file('cubesat.tle', filename='gp.php?GROUP=cubesat', reload=True) print('Downloaded and loaded satellites.') ``` -------------------------------- ### Create a Star Object with Coordinates Source: https://github.com/skyfielders/python-skyfield/blob/master/documentation/stars.rst Instantiates a Star object using traditional base-60 coordinates for right ascension and declination. Calculates astrometric position relative to Earth. ```python from skyfield.api import Star, load planets = load('de421.bsp') earth = planets['earth'] barnard = Star(ra_hours=(17, 57, 48.49803), dec_degrees=(4, 41, 36.2072)) ts = load.timescale() t = ts.now() astrometric = earth.at(t).observe(barnard) ra, dec, distance = astrometric.radec() print(ra) print(dec) ``` -------------------------------- ### Find Sunrises using Skyfield Source: https://github.com/skyfielders/python-skyfield/blob/master/documentation/almanac.rst Compute sunrise times for a given observer and celestial body between a start and end time. The `find_risings` function returns the times and a boolean array indicating if a rising was detected. ```python t0 = ts.utc(2018, 9, 12, 4) t1 = ts.utc(2018, 9, 14, 4) t, y = almanac.find_risings(observer, sun, t0, t1) print(t.utc_iso(' ')) print(y) ``` -------------------------------- ### Compute Object Position at a Specific Time Source: https://context7.com/skyfielders/python-skyfield/llms.txt Use the `.at(t)` method on planet or satellite objects to get their position (and velocity) in the ICRS frame at a given time `t`. This method supports both scalar and array Time objects. ```python from skyfield.api import load ts = load.timescale() planets = load('de421.bsp') earth, jupiter = planets['earth'], planets['jupiter barycenter'] t = ts.utc(2025, 7, 4, 0, 0, 0) position = earth.at(t) # Barycentric position of Earth print(position) # # Array of times. t_range = ts.utc(2025, 7, range(1, 8)) # one week positions = earth.at(t_range) print(positions.xyz.au.shape) # (3, 7) ``` -------------------------------- ### Generate Astrometric RA/Dec Source: https://github.com/skyfielders/python-skyfield/blob/master/documentation/positions.rst Use this method to get astrometric RA/Dec coordinates. These are reference coordinates suitable for star charts and catalogs, independent of specific observation times. They are based on the ICRS standard with the J2000 equinox. ```python # Astrometric RA/Dec. ra, dec, distance = astrometric.radec() print('RA:', ra) print('Dec:', dec) print('Distance:', distance) ``` -------------------------------- ### Add Skyfield Reference Source: https://github.com/skyfielders/python-skyfield/blob/master/Contrib.rst Add the official Skyfield repository as a remote to your local repository to fetch updates. ```bash git remote add skyfield git@github.com:skyfielders/python-skyfield.git ``` ```bash git fetch skyfield ``` ```bash git branch -r ``` -------------------------------- ### Create Development Branch Source: https://github.com/skyfielders/python-skyfield/blob/master/Contrib.rst Create a new branch for your development work to isolate changes. ```bash git checkout -b Issue31 ``` -------------------------------- ### Plot Satellite Altitude During Re-entry Source: https://github.com/skyfielders/python-skyfield/blob/master/documentation/example-plots.rst Shows the decreasing altitude of a satellite as it re-enters the atmosphere. The code uses matplotlib and includes custom tick marks based on the date. This example demonstrates plotting orbital decay. ```python from skyfield.api import load, EarthSatellite from skyfield.timelib import Time import matplotlib.pyplot as plt import matplotlib.dates as mdates # Load ephemeris ephemeris = load('de421.bsp') # Example satellite TLE (replace with actual TLE if available) line1 = '1 25544U 98067A 23300.50000000 .00000000 00000-0 10000-3 0 999' line2 = '2 25544 51.6434 247.4627 0006703 130.5350 325.0287 15.49390000000000' satellite = EarthSatellite(line1, line2, 'ISS (ZARYA)', ephemeris) # Time range for re-entry (example) ts = load.timescale() start_time = ts.utc(2023, 10, 26, 12, 0, 0) end_time = ts.utc(2023, 10, 26, 13, 0, 0) t = ts.linspace(start_time, end_time, 100) # Compute satellite altitude geocentric = load('wgs84.earth').at(t) subpoint = satellite.at(t).subpoint() altitude = subpoint.elevation.km # Plotting (example using matplotlib) plt.figure(figsize=(10, 6)) plt.plot(t.utc_datetime(), altitude) # Format x-axis for dates plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%H:%M:%S')) plt.gca().xaxis.set_major_locator(mdates.MinuteLocator(interval=10)) plt.xlabel('Time (UTC)') plt.ylabel('Altitude (km)') plt.title('Satellite Altitude During Re-entry') plt.grid(True) plt.tight_layout() plt.show() ``` -------------------------------- ### Initialize Star with Custom Epoch Source: https://github.com/skyfielders/python-skyfield/blob/master/documentation/stars.rst Use the 'epoch' argument when creating a Star object to specify positions from catalogs that use epochs other than J2000. This is useful for historical or specialized star data. ```python hipparcos_epoch = ts.tt(1991.25) barnard2 = Star(ra_hours=(17, 57, 48.97), dec_degrees=(4, 40, 5.8), ra_mas_per_year=-797.84, dec_mas_per_year=+10326.93, epoch=hipparcos_epoch) ra, dec, distance = earth.at(t).observe(barnard2).radec() print(ra) print(dec) ``` -------------------------------- ### Get Cartesian and Spherical ICRS Coordinates Source: https://github.com/skyfielders/python-skyfield/blob/master/documentation/coordinates.rst Use the `.xyz` attribute for Cartesian coordinates and `.radec()` for spherical coordinates in the ICRS system. The `.xyz` attribute returns a Distance object supporting various units like AU. ```python from skyfield.api import load ts = load.timescale() t = ts.utc(2021, 12, 2, 14, 7) eph = load('de421.bsp') earth, mars = eph['earth'], eph['mars'] position = earth.at(t).observe(mars) print('Cartesian ICRS:') x, y, z = position.xyz.au print(' x = {:.3f} au'.format(x)) print(' y = {:.3f} au'.format(y)) print(' z = {:.3f} au'.format(z)) print() print('Spherical ICRS:') ra, dec, distance = position.radec() print(' ', ra, 'right ascension') print(' ', dec, 'declination') print(' ', distance, 'distance') ``` -------------------------------- ### Load Local Ephemeris File Source: https://github.com/skyfielders/python-skyfield/blob/master/documentation/api.rst Load a local ephemeris file (e.g., DE405) using `load_file`. ```python # File you already have. from skyfield.api import load_file planets = load_file('~/Downloads/de405.bsp') ``` -------------------------------- ### Convert Altitude and Azimuth to Right Ascension and Declination Source: https://github.com/skyfielders/python-skyfield/blob/master/documentation/examples.rst This example shows how to convert altitude and azimuth coordinates to right ascension and declination using Skyfield. Ensure you have loaded the timescale and defined the observer's geographic location and time. ```python from skyfield import api ts = api.load.timescale() t = ts.utc(2019, 9, 13, 20) geographic = api.wgs84.latlon(latitude_degrees=42, longitude_degrees=-87) observer = geographic.at(t) pos = observer.from_altaz(alt_degrees=90, az_degrees=0) ra, dec, distance = pos.radec() print(ra) print(dec) ``` -------------------------------- ### Download and Open JPL Ephemeris DE421 Source: https://github.com/skyfielders/python-skyfield/blob/master/documentation/planets.rst Loads the DE421 ephemeris file and retrieves the position of Mars Barycenter at a specific time. Ensure the ephemeris file is downloaded to the correct directory. ```python from skyfield.api import load ts = load.timescale() t = ts.utc(2021, 2, 26, 15, 19) planets = load('de421.bsp') # ephemeris DE421 mars = planets['Mars Barycenter'] barycentric = mars.at(t) ``` -------------------------------- ### Generate Apparent RA/Dec Source: https://github.com/skyfielders/python-skyfield/blob/master/documentation/positions.rst Use this method to get apparent RA/Dec coordinates for practical applications like pointing a telescope. These coordinates account for real-world effects like aberration and deflection, reflecting the object's actual position in the sky at a given time. ```python # Apparent RA/Dec. ra, dec, distance = apparent.radec('date') print('RA:', ra) print('Dec:', dec) print('Distance:', distance) ``` -------------------------------- ### Instantiate EarthSatellite from TLE Strings Source: https://github.com/skyfielders/python-skyfield/blob/master/documentation/earth-satellites.rst Creates an EarthSatellite object directly from two TLE (Two-Line Element) strings. Useful when TLE data is already available. ```python from skyfield.api import EarthSatellite ts = load.timescale() line1 = '1 25544U 98067A 14020.93268519 .00009878 00000-0 18200-3 0 5082' line2 = '2 25544 51.6498 109.4756 0003572 55.9686 274.8005 15.49815350868473' satellite = EarthSatellite(line1, line2, 'ISS (ZARYA)', ts) print(satellite) ``` -------------------------------- ### Create Geographic Position with Elevation Source: https://github.com/skyfielders/python-skyfield/blob/master/documentation/earth-satellites.rst Manually build a subpoint on Earth using latitude, longitude, and a specified elevation above the WGS84 ellipsoid. ```python elevation_m = 123.0 subpoint = wgs84.latlon(lat.degrees, lon.degrees, elevation_m) ``` -------------------------------- ### Get leap second flag with datetime Source: https://github.com/skyfielders/python-skyfield/blob/master/documentation/time.rst Shows how to use Skyfield's `astimezone_and_leap_second()` method to retrieve both the datetime object and a flag indicating if a leap second was present. This is crucial for applications that must use datetime objects but still need to account for leap seconds. ```python # Asking for the leap_second flag to learn the whole story dt, leap_second = t.astimezone_and_leap_second(eastern) for dt_i, leap_second_i in zip(dt, leap_second): print('{0} leap_second = {1}'.format(dt_i, leap_second_i)) ``` -------------------------------- ### Define and Plot Venus Elongation in Skyfield Source: https://github.com/skyfielders/python-skyfield/blob/master/documentation/searches.rst This snippet defines a function to calculate Venus's elongation from the Sun as seen from Earth and plots it over time. It uses `apparent()` to get the apparent positions and `separation_from()` to find the angle between celestial bodies. Ensure sufficient data points are used for accurate plotting. ```python from skyfield.api import load import matplotlib.pyplot as plt ts = load.timescale() planets = load.ephemeris('de421.bsp') earth = planets['earth'] venus = planets['venus'] sun = planets['sun'] def venus_elongation_degrees(t): e = earth.at(t) s = e.observe(sun).apparent() v = e.observe(venus).apparent() return s.separation_from(v).degrees fig, ax = plt.subplots(figsize=(5, 2)) t = ts.utc(2018, 1, range(366 * 5)) ax.plot(t.J, venus_elongation_degrees(t)) ax.set(title='Elongation of Venus (degrees)', xlabel='Year') ax.grid() fig.tight_layout() fig.savefig('venus-elongation.png') ``` -------------------------------- ### Create Ephemeris Excerpt from Command Line Source: https://github.com/skyfielders/python-skyfield/blob/master/documentation/planets.rst Use the jplephem command-line tool to create a smaller excerpt of a large ephemeris file for a specified date range. This is useful for reducing file size when only a portion of the data is needed. ```bash $ u=https://naif.jpl.nasa.gov/pub/naif/generic_kernels/spk/satellites/jup310.bsp $ python -m jplephem excerpt 2018/1/1 2018/1/15 $u jup_excerpt.bsp ``` -------------------------------- ### find_settings Source: https://github.com/skyfielders/python-skyfield/blob/master/documentation/api-almanac.rst Finds the times of settings for celestial bodies. ```APIDOC ## find_settings ### Description Finds the times of settings for celestial bodies. ### Parameters (Details not provided in source) ``` -------------------------------- ### Formatting Angles Source: https://github.com/skyfielders/python-skyfield/blob/master/documentation/api-units.rst Demonstrates how to format Angle objects into various string representations, including decimal degrees, hours, and custom formats. ```APIDOC ## Formatting angles To display an angle as decimal degrees or hours, ask the angle for its `.hours` or `.degrees` attribute and then use any normal Python mechanism for formatting a float. For example: ```python from skyfield.units import Angle ra, dec = Angle(hours=5.5877286), Angle(degrees=-5.38731536) print('RA {:.8f} hours'.format(ra.hours)) print('Dec {:+.8f} degrees'.format(dec.degrees)) ``` If you let Skyfield do the formatting instead, then hours are split into 60 minutes of 60 seconds each, and degrees are split into 60 arcminutes of 60 arcseconds each: ```python print('RA', ra) print('Dec', dec) ``` If you want more control over the display of minutes and seconds, you can call an angle’s “hours as a string” method :meth:`~Angle.hstr` or “degrees as a string” method :meth:`~Angle.dstr`. The simplest adjustment you can make is to specify the number of decimal `places` that will be shown in the seconds field. ```python print('RA', ra.hstr(places=4)) print('Dec', dec.dstr(places=4)) ``` Using plain ASCII lets Skyfield support as many operating systems and output media as possible. But it would be more correct to denote arcseconds and arcminutes with the Unicode symbols PRIME and DOUBLE PRIME, and to use the Unicode DEGREE SIGN to mark the whole number: −5°23′14.3″. If you want to override Skyfield’s default notation to create either the string above, or any other notation, then give :meth:`~Angle.hstr` or :meth:`~Angle.dstr` a `format=` string of your own. It should use the syntax of Python’s `str.format() `_ method. For example, here’s the exact string you would use to format an angle in degrees, arcminutes, and arcseconds using the traditional typographic symbols discussed above: ```python print(dec.dstr(format=u'{0}{1}°{2:02}′{3:02}.{4:0{5}}″')) ``` Skyfield will call your string’s format method with these six arguments: * `{0}`: An ASCII hyphen `'-'` if the angle is negative, else the empty string. If you want positive angles to be decorated with a plus sign, try using `{0:+>1}` which tells Python, “display positional parameter 0, padding the field to one character wide if it’s less than one character already, and use the `+` character to do the padding.” * `{1}`: The number of whole hours or degrees. * `{2}`: The number of whole minutes. * `{3}`: The number of whole seconds. * `{4}`: The fractions of a second. Be sure to pad this field to the number of `places=` you’ve requested, or else a fraction like `.0012` will format incorrectly as `.12`. If you have asked for `places=3`, for example, you’ll want to display this field as `{4:03}`. (See also the next item.) * `{5}`: The number of `places=` you requested, which you will probably use like `{4:0{5}}` when formatting field 4. You can use this in case you might not know the number of places ahead of time, for example if the number of places is configured by your user. ```