Astronomy and astrophysics core library providing comprehensive tools for astronomical computations and data handling
—
Quality
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
High-precision time handling with support for multiple time scales (UTC, TAI, TT, etc.), time formats (JD, MJD, ISO), and astronomical time calculations.
High-precision time representation supporting multiple time scales with automatic conversions and astronomical time standards.
class Time:
"""
High-precision time representation with multiple formats and scales.
Parameters:
- val: time value(s) in specified format
- val2: optional second time value for high precision
- format: time format ('jd', 'mjd', 'iso', 'datetime', etc.)
- scale: time scale ('utc', 'tai', 'tt', 'tcg', 'tdb', etc.)
- precision: decimal precision for output
- in_subfmt: sub-format specification
- out_subfmt: output sub-format specification
- location: Earth location for time scale transformations
"""
def __init__(self, val, val2=None, format=None, scale=None, precision=None,
in_subfmt=None, out_subfmt=None, location=None): ...
# Time scale properties (read-only conversions)
@property
def jd(self):
"""Julian Date in current time scale."""
@property
def mjd(self):
"""Modified Julian Date (JD - 2400000.5)."""
@property
def unix(self):
"""Unix timestamp (seconds since 1970-01-01 00:00:00 UTC)."""
@property
def iso(self):
"""ISO 8601 format string."""
@property
def isot(self):
"""ISO 8601 format with 'T' separator."""
@property
def yday(self):
"""Year and day of year."""
@property
def datetime(self):
"""Python datetime object."""
@property
def fits(self):
"""FITS format string."""
@property
def gps(self):
"""GPS time (seconds since 1980-01-06 00:00:00 UTC)."""
@property
def plot_date(self):
"""Matplotlib plot_date format."""
# Time scale conversions
@property
def utc(self):
"""Convert to UTC time scale."""
@property
def tai(self):
"""Convert to TAI (International Atomic Time) scale."""
@property
def tt(self):
"""Convert to TT (Terrestrial Time) scale."""
@property
def tcg(self):
"""Convert to TCG (Geocentric Coordinate Time) scale."""
@property
def tcb(self):
"""Convert to TCB (Barycentric Coordinate Time) scale."""
@property
def tdb(self):
"""Convert to TDB (Barycentric Dynamical Time) scale."""
@property
def ut1(self):
"""Convert to UT1 (Universal Time) scale."""
@property
def gps(self):
"""Convert to GPS time scale."""
# Time arithmetic methods
def __add__(self, other):
"""Add TimeDelta to Time."""
def __sub__(self, other):
"""Subtract Time or TimeDelta from Time."""
def __lt__(self, other): ...
def __le__(self, other): ...
def __eq__(self, other): ...
def __ge__(self, other): ...
def __gt__(self, other): ...
# Utility methods
def copy(self, format=None):
"""Copy with optional format change."""
def replicate(self, format=None, copy=False):
"""Replicate with optional format change."""
def to_value(self, format=None, subfmt=None):
"""Get time value in specified format."""
@classmethod
def now(cls):
"""Current time in UTC."""
@classmethod
def strptime(cls, time_string, format_string):
"""Parse time string using strptime format."""Time difference calculations with support for time arithmetic and duration measurements.
class TimeDelta:
"""
Difference between two times with high precision.
Parameters:
- val: time difference value
- val2: optional second value for high precision
- format: format specification ('jd', 'sec', 'datetime', etc.)
- scale: time scale for the difference
"""
def __init__(self, val, val2=None, format=None, scale=None): ...
# Format properties
@property
def jd(self):
"""Time difference in Julian days."""
@property
def sec(self):
"""Time difference in seconds."""
@property
def to_datetime(self):
"""Convert to datetime.timedelta object."""
# Arithmetic operations
def __add__(self, other): ...
def __sub__(self, other): ...
def __mul__(self, other): ...
def __truediv__(self, other): ...
def __neg__(self): ...
def __abs__(self): ...
# Comparison operations
def __lt__(self, other): ...
def __le__(self, other): ...
def __eq__(self, other): ...
def __ge__(self, other): ...
def __gt__(self, other): ...
def to(self, unit):
"""Convert to astropy Quantity with time units."""Built-in time format support for various astronomical and civil time representations.
class TimeFormat:
"""Base class for time formats."""
# Built-in formats available as format strings:
# 'jd' - Julian Date
# 'mjd' - Modified Julian Date
# 'unix' - Unix timestamp
# 'iso' - ISO 8601 format
# 'isot' - ISO 8601 with 'T' separator
# 'yday' - Year and day-of-year
# 'datetime' - Python datetime objects
# 'fits' - FITS standard format
# 'gps' - GPS time
# 'cxcsec' - Chandra X-ray Center seconds
# 'unix_tai' - Unix timestamp in TAI
# 'plot_date' - Matplotlib date format
# Sub-formats for fine control:
# 'date_hms' - Date with hours:minutes:seconds
# 'date_hm' - Date with hours:minutes
# 'date' - Date only
# 'longdate_hms' - Long date format with HMS
# 'longdate' - Long date formatBuilt-in support for leap seconds, ΔUT1 corrections, and relativistic time scale transformations.
def update_leap_seconds(files=None):
"""
Update leap second table from IERS data.
Parameters:
- files: list of files to read leap seconds from
"""
class IERS_A:
"""IERS Bulletin A data for Earth rotation parameters."""
@classmethod
def open(cls, file=None, cache=False):
"""Open IERS-A table from file or download."""
class IERS_B:
"""IERS Bulletin B data for Earth rotation parameters."""
def get_delta_ut1_utc(time):
"""
Get ΔUT1-UTC correction for specified time.
Parameters:
- time: Time object
Returns:
TimeDelta: ΔUT1-UTC correction
"""
# Access to leap second table
from astropy.utils.iers import LeapSeconds
leap_seconds = LeapSeconds.auto_open()Support for vectorized time operations including array creation, slicing, and broadcasting.
# Time arrays support all numpy-like operations:
# Array creation
times = Time(['2023-01-01', '2023-01-02', '2023-01-03'])
# Slicing and indexing
first_time = times[0]
subset = times[1:]
# Shape manipulation
times.reshape(3, 1)
# Broadcasting with TimeDelta
delta = TimeDelta([1, 2, 3], format='jd')
future_times = times + delta
# Aggregation operations
earliest = times.min()
latest = times.max()Limited time zone support for civil time applications with UTC conversions.
# Time zones through datetime integration
import datetime
import pytz
# Create timezone-aware datetime
tz = pytz.timezone('US/Pacific')
dt = datetime.datetime(2023, 6, 15, 12, 0, 0, tzinfo=tz)
# Convert to Time object (automatically converts to UTC)
t = Time(dt)
# Convert back to timezone-aware datetime
dt_back = t.to_datetime(timezone=tz)from astropy.time import Time, TimeDelta
import astropy.units as u
# Create times in different formats
t1 = Time('2023-08-15 12:34:56', format='iso', scale='utc')
t2 = Time(2460176.024, format='jd', scale='utc')
t3 = Time.now()
# Convert between formats
print(f"ISO: {t1.iso}")
print(f"JD: {t1.jd}")
print(f"MJD: {t1.mjd}")
print(f"Unix: {t1.unix}")
# Convert between time scales
print(f"UTC: {t1.utc.iso}")
print(f"TAI: {t1.tai.iso}")
print(f"TT: {t1.tt.iso}")# Time differences
t1 = Time('2023-01-01 00:00:00')
t2 = Time('2023-01-15 12:30:00')
duration = t2 - t1
print(f"Duration: {duration.jd} days")
print(f"Duration: {duration.sec} seconds")
# Add time intervals
delta = TimeDelta(30, format='jd') # 30 days
future_time = t1 + delta
# Convert to astropy units
duration_hours = duration.to(u.hour)
print(f"Duration: {duration_hours}")# High precision using val2 parameter
high_precision_time = Time(2460000.0, 0.123456789, format='jd')
# Barycentric corrections for precision astronomy
from astropy.coordinates import EarthLocation, SkyCoord
location = EarthLocation.of_site('Keck')
target = SkyCoord.from_name('Vega')
# Get barycentric time correction
obs_time = Time('2023-08-15 10:30:00', location=location)
ltt_bary = obs_time.light_travel_time(target)
bary_time = obs_time.tdb + ltt_bary
print(f"Observatory time: {obs_time.iso}")
print(f"Barycentric time: {bary_time.iso}")import numpy as np
# Create time series
start_time = Time('2023-01-01 00:00:00')
time_array = start_time + TimeDelta(np.arange(365), format='jd')
# Find specific times
summer_solstice = Time('2023-06-21')
closest_idx = np.argmin(np.abs(time_array - summer_solstice))
closest_time = time_array[closest_idx]
print(f"Closest observation to summer solstice: {closest_time.iso}")
# Time masking
recent_times = time_array[time_array > Time('2023-06-01')]
print(f"Observations after June 1: {len(recent_times)}")from astropy.coordinates import get_sun, EarthLocation, AltAz
# Solar observations
location = EarthLocation.of_site('ALMA')
obs_times = Time('2023-08-15 06:00:00') + TimeDelta(np.arange(0, 12*60, 10), format='sec')
# Calculate sun positions over time
sun_coords = get_sun(obs_times)
sun_altaz = sun_coords.transform_to(AltAz(obstime=obs_times, location=location))
# Find when sun is above 30 degrees elevation
good_observing = sun_altaz.alt > 30*u.degree
observing_times = obs_times[good_observing]
print(f"Good observing window: {observing_times[0].iso} to {observing_times[-1].iso}")# Parse various formats
times = [
Time('2023-08-15T12:34:56.789'), # ISO with microseconds
Time('Aug 15, 2023 12:34:56'), # Human readable
Time(datetime.datetime.now()), # Python datetime
Time('2023:227:12:34:56.789'), # Day-of-year format
]
# Custom format output
t = Time.now()
print(f"Custom format: {t.strftime('%Y-%m-%d %H:%M:%S %Z')}")
# High precision output
t_precise = Time('2023-08-15 12:34:56.123456789')
print(f"Nanosecond precision: {t_precise.iso}")# Precise time scale conversions for pulsar timing
pulsar_time_utc = Time('2023-08-15 12:34:56.123456789', scale='utc')
# Convert to barycentric dynamical time for pulsar analysis
pulsar_time_tdb = pulsar_time_utc.tdb
# Convert to terrestrial time for laboratory comparison
pulsar_time_tt = pulsar_time_utc.tt
print(f"UTC: {pulsar_time_utc.iso}")
print(f"TDB: {pulsar_time_tdb.iso}")
print(f"TT: {pulsar_time_tt.iso}")
# Time differences between scales
tt_minus_utc = (pulsar_time_tt - pulsar_time_utc).sec
print(f"TT - UTC = {tt_minus_utc:.6f} seconds")