0
# Time Handling
1
2
High-precision time handling with support for multiple time scales (UTC, TAI, TT, etc.), time formats (JD, MJD, ISO), and astronomical time calculations.
3
4
## Capabilities
5
6
### Time Representation and Scales
7
8
High-precision time representation supporting multiple time scales with automatic conversions and astronomical time standards.
9
10
```python { .api }
11
class Time:
12
"""
13
High-precision time representation with multiple formats and scales.
14
15
Parameters:
16
- val: time value(s) in specified format
17
- val2: optional second time value for high precision
18
- format: time format ('jd', 'mjd', 'iso', 'datetime', etc.)
19
- scale: time scale ('utc', 'tai', 'tt', 'tcg', 'tdb', etc.)
20
- precision: decimal precision for output
21
- in_subfmt: sub-format specification
22
- out_subfmt: output sub-format specification
23
- location: Earth location for time scale transformations
24
"""
25
def __init__(self, val, val2=None, format=None, scale=None, precision=None,
26
in_subfmt=None, out_subfmt=None, location=None): ...
27
28
# Time scale properties (read-only conversions)
29
@property
30
def jd(self):
31
"""Julian Date in current time scale."""
32
33
@property
34
def mjd(self):
35
"""Modified Julian Date (JD - 2400000.5)."""
36
37
@property
38
def unix(self):
39
"""Unix timestamp (seconds since 1970-01-01 00:00:00 UTC)."""
40
41
@property
42
def iso(self):
43
"""ISO 8601 format string."""
44
45
@property
46
def isot(self):
47
"""ISO 8601 format with 'T' separator."""
48
49
@property
50
def yday(self):
51
"""Year and day of year."""
52
53
@property
54
def datetime(self):
55
"""Python datetime object."""
56
57
@property
58
def fits(self):
59
"""FITS format string."""
60
61
@property
62
def gps(self):
63
"""GPS time (seconds since 1980-01-06 00:00:00 UTC)."""
64
65
@property
66
def plot_date(self):
67
"""Matplotlib plot_date format."""
68
69
# Time scale conversions
70
@property
71
def utc(self):
72
"""Convert to UTC time scale."""
73
74
@property
75
def tai(self):
76
"""Convert to TAI (International Atomic Time) scale."""
77
78
@property
79
def tt(self):
80
"""Convert to TT (Terrestrial Time) scale."""
81
82
@property
83
def tcg(self):
84
"""Convert to TCG (Geocentric Coordinate Time) scale."""
85
86
@property
87
def tcb(self):
88
"""Convert to TCB (Barycentric Coordinate Time) scale."""
89
90
@property
91
def tdb(self):
92
"""Convert to TDB (Barycentric Dynamical Time) scale."""
93
94
@property
95
def ut1(self):
96
"""Convert to UT1 (Universal Time) scale."""
97
98
@property
99
def gps(self):
100
"""Convert to GPS time scale."""
101
102
# Time arithmetic methods
103
def __add__(self, other):
104
"""Add TimeDelta to Time."""
105
106
def __sub__(self, other):
107
"""Subtract Time or TimeDelta from Time."""
108
109
def __lt__(self, other): ...
110
def __le__(self, other): ...
111
def __eq__(self, other): ...
112
def __ge__(self, other): ...
113
def __gt__(self, other): ...
114
115
# Utility methods
116
def copy(self, format=None):
117
"""Copy with optional format change."""
118
119
def replicate(self, format=None, copy=False):
120
"""Replicate with optional format change."""
121
122
def to_value(self, format=None, subfmt=None):
123
"""Get time value in specified format."""
124
125
@classmethod
126
def now(cls):
127
"""Current time in UTC."""
128
129
@classmethod
130
def strptime(cls, time_string, format_string):
131
"""Parse time string using strptime format."""
132
```
133
134
### Time Differences and Durations
135
136
Time difference calculations with support for time arithmetic and duration measurements.
137
138
```python { .api }
139
class TimeDelta:
140
"""
141
Difference between two times with high precision.
142
143
Parameters:
144
- val: time difference value
145
- val2: optional second value for high precision
146
- format: format specification ('jd', 'sec', 'datetime', etc.)
147
- scale: time scale for the difference
148
"""
149
def __init__(self, val, val2=None, format=None, scale=None): ...
150
151
# Format properties
152
@property
153
def jd(self):
154
"""Time difference in Julian days."""
155
156
@property
157
def sec(self):
158
"""Time difference in seconds."""
159
160
@property
161
def to_datetime(self):
162
"""Convert to datetime.timedelta object."""
163
164
# Arithmetic operations
165
def __add__(self, other): ...
166
def __sub__(self, other): ...
167
def __mul__(self, other): ...
168
def __truediv__(self, other): ...
169
def __neg__(self): ...
170
def __abs__(self): ...
171
172
# Comparison operations
173
def __lt__(self, other): ...
174
def __le__(self, other): ...
175
def __eq__(self, other): ...
176
def __ge__(self, other): ...
177
def __gt__(self, other): ...
178
179
def to(self, unit):
180
"""Convert to astropy Quantity with time units."""
181
```
182
183
### Time Formats
184
185
Built-in time format support for various astronomical and civil time representations.
186
187
```python { .api }
188
class TimeFormat:
189
"""Base class for time formats."""
190
191
# Built-in formats available as format strings:
192
193
# 'jd' - Julian Date
194
# 'mjd' - Modified Julian Date
195
# 'unix' - Unix timestamp
196
# 'iso' - ISO 8601 format
197
# 'isot' - ISO 8601 with 'T' separator
198
# 'yday' - Year and day-of-year
199
# 'datetime' - Python datetime objects
200
# 'fits' - FITS standard format
201
# 'gps' - GPS time
202
# 'cxcsec' - Chandra X-ray Center seconds
203
# 'unix_tai' - Unix timestamp in TAI
204
# 'plot_date' - Matplotlib date format
205
206
# Sub-formats for fine control:
207
# 'date_hms' - Date with hours:minutes:seconds
208
# 'date_hm' - Date with hours:minutes
209
# 'date' - Date only
210
# 'longdate_hms' - Long date format with HMS
211
# 'longdate' - Long date format
212
```
213
214
### Leap Seconds and Time Corrections
215
216
Built-in support for leap seconds, ΔUT1 corrections, and relativistic time scale transformations.
217
218
```python { .api }
219
def update_leap_seconds(files=None):
220
"""
221
Update leap second table from IERS data.
222
223
Parameters:
224
- files: list of files to read leap seconds from
225
"""
226
227
class IERS_A:
228
"""IERS Bulletin A data for Earth rotation parameters."""
229
230
@classmethod
231
def open(cls, file=None, cache=False):
232
"""Open IERS-A table from file or download."""
233
234
class IERS_B:
235
"""IERS Bulletin B data for Earth rotation parameters."""
236
237
def get_delta_ut1_utc(time):
238
"""
239
Get ΔUT1-UTC correction for specified time.
240
241
Parameters:
242
- time: Time object
243
244
Returns:
245
TimeDelta: ΔUT1-UTC correction
246
"""
247
248
# Access to leap second table
249
from astropy.utils.iers import LeapSeconds
250
leap_seconds = LeapSeconds.auto_open()
251
```
252
253
### Time Array Operations
254
255
Support for vectorized time operations including array creation, slicing, and broadcasting.
256
257
```python { .api }
258
# Time arrays support all numpy-like operations:
259
260
# Array creation
261
times = Time(['2023-01-01', '2023-01-02', '2023-01-03'])
262
263
# Slicing and indexing
264
first_time = times[0]
265
subset = times[1:]
266
267
# Shape manipulation
268
times.reshape(3, 1)
269
270
# Broadcasting with TimeDelta
271
delta = TimeDelta([1, 2, 3], format='jd')
272
future_times = times + delta
273
274
# Aggregation operations
275
earliest = times.min()
276
latest = times.max()
277
```
278
279
### Time Zone Support
280
281
Limited time zone support for civil time applications with UTC conversions.
282
283
```python { .api }
284
# Time zones through datetime integration
285
import datetime
286
import pytz
287
288
# Create timezone-aware datetime
289
tz = pytz.timezone('US/Pacific')
290
dt = datetime.datetime(2023, 6, 15, 12, 0, 0, tzinfo=tz)
291
292
# Convert to Time object (automatically converts to UTC)
293
t = Time(dt)
294
295
# Convert back to timezone-aware datetime
296
dt_back = t.to_datetime(timezone=tz)
297
```
298
299
## Usage Examples
300
301
### Basic Time Creation and Conversion
302
303
```python
304
from astropy.time import Time, TimeDelta
305
import astropy.units as u
306
307
# Create times in different formats
308
t1 = Time('2023-08-15 12:34:56', format='iso', scale='utc')
309
t2 = Time(2460176.024, format='jd', scale='utc')
310
t3 = Time.now()
311
312
# Convert between formats
313
print(f"ISO: {t1.iso}")
314
print(f"JD: {t1.jd}")
315
print(f"MJD: {t1.mjd}")
316
print(f"Unix: {t1.unix}")
317
318
# Convert between time scales
319
print(f"UTC: {t1.utc.iso}")
320
print(f"TAI: {t1.tai.iso}")
321
print(f"TT: {t1.tt.iso}")
322
```
323
324
### Time Arithmetic and Differences
325
326
```python
327
# Time differences
328
t1 = Time('2023-01-01 00:00:00')
329
t2 = Time('2023-01-15 12:30:00')
330
331
duration = t2 - t1
332
print(f"Duration: {duration.jd} days")
333
print(f"Duration: {duration.sec} seconds")
334
335
# Add time intervals
336
delta = TimeDelta(30, format='jd') # 30 days
337
future_time = t1 + delta
338
339
# Convert to astropy units
340
duration_hours = duration.to(u.hour)
341
print(f"Duration: {duration_hours}")
342
```
343
344
### High-Precision Time Calculations
345
346
```python
347
# High precision using val2 parameter
348
high_precision_time = Time(2460000.0, 0.123456789, format='jd')
349
350
# Barycentric corrections for precision astronomy
351
from astropy.coordinates import EarthLocation, SkyCoord
352
353
location = EarthLocation.of_site('Keck')
354
target = SkyCoord.from_name('Vega')
355
356
# Get barycentric time correction
357
obs_time = Time('2023-08-15 10:30:00', location=location)
358
ltt_bary = obs_time.light_travel_time(target)
359
bary_time = obs_time.tdb + ltt_bary
360
361
print(f"Observatory time: {obs_time.iso}")
362
print(f"Barycentric time: {bary_time.iso}")
363
```
364
365
### Time Arrays and Vectorization
366
367
```python
368
import numpy as np
369
370
# Create time series
371
start_time = Time('2023-01-01 00:00:00')
372
time_array = start_time + TimeDelta(np.arange(365), format='jd')
373
374
# Find specific times
375
summer_solstice = Time('2023-06-21')
376
closest_idx = np.argmin(np.abs(time_array - summer_solstice))
377
closest_time = time_array[closest_idx]
378
379
print(f"Closest observation to summer solstice: {closest_time.iso}")
380
381
# Time masking
382
recent_times = time_array[time_array > Time('2023-06-01')]
383
print(f"Observations after June 1: {len(recent_times)}")
384
```
385
386
### Astronomical Time Applications
387
388
```python
389
from astropy.coordinates import get_sun, EarthLocation, AltAz
390
391
# Solar observations
392
location = EarthLocation.of_site('ALMA')
393
obs_times = Time('2023-08-15 06:00:00') + TimeDelta(np.arange(0, 12*60, 10), format='sec')
394
395
# Calculate sun positions over time
396
sun_coords = get_sun(obs_times)
397
sun_altaz = sun_coords.transform_to(AltAz(obstime=obs_times, location=location))
398
399
# Find when sun is above 30 degrees elevation
400
good_observing = sun_altaz.alt > 30*u.degree
401
observing_times = obs_times[good_observing]
402
403
print(f"Good observing window: {observing_times[0].iso} to {observing_times[-1].iso}")
404
```
405
406
### Time Format Parsing and Customization
407
408
```python
409
# Parse various formats
410
times = [
411
Time('2023-08-15T12:34:56.789'), # ISO with microseconds
412
Time('Aug 15, 2023 12:34:56'), # Human readable
413
Time(datetime.datetime.now()), # Python datetime
414
Time('2023:227:12:34:56.789'), # Day-of-year format
415
]
416
417
# Custom format output
418
t = Time.now()
419
print(f"Custom format: {t.strftime('%Y-%m-%d %H:%M:%S %Z')}")
420
421
# High precision output
422
t_precise = Time('2023-08-15 12:34:56.123456789')
423
print(f"Nanosecond precision: {t_precise.iso}")
424
```
425
426
### Time Scale Conversions for Precision Work
427
428
```python
429
# Precise time scale conversions for pulsar timing
430
pulsar_time_utc = Time('2023-08-15 12:34:56.123456789', scale='utc')
431
432
# Convert to barycentric dynamical time for pulsar analysis
433
pulsar_time_tdb = pulsar_time_utc.tdb
434
435
# Convert to terrestrial time for laboratory comparison
436
pulsar_time_tt = pulsar_time_utc.tt
437
438
print(f"UTC: {pulsar_time_utc.iso}")
439
print(f"TDB: {pulsar_time_tdb.iso}")
440
print(f"TT: {pulsar_time_tt.iso}")
441
442
# Time differences between scales
443
tt_minus_utc = (pulsar_time_tt - pulsar_time_utc).sec
444
print(f"TT - UTC = {tt_minus_utc:.6f} seconds")
445
```