0
# Time Epoch Conversion
1
2
Comprehensive time handling system supporting all three CDF epoch formats with conversion between CDF epochs, Unix timestamps, numpy datetime64, and human-readable strings. The CDFepoch class provides static methods for working with time data in scientific applications.
3
4
## CDF Epoch Formats
5
6
CDF supports three time formats, each optimized for different precision and range requirements:
7
8
1. **CDF_EPOCH**: Milliseconds since Year 0 (8-byte float)
9
2. **CDF_EPOCH16**: Picoseconds since Year 0 (16-byte complex)
10
3. **CDF_TIME_TT2000**: Nanoseconds since J2000 with leap seconds (8-byte integer)
11
12
## Capabilities
13
14
### Generic Time Operations
15
16
Automatic format detection and conversion operations that work with any CDF epoch type.
17
18
```python { .api }
19
class CDFepoch:
20
@staticmethod
21
def encode(epochs, iso_8601=True):
22
"""
23
Encode CDF epochs to human-readable strings.
24
25
Parameters:
26
- epochs (int | float | complex | array-like): CDF epoch values of any type
27
- iso_8601 (bool): Use ISO 8601 format if True, CDF format if False
28
29
Returns:
30
str | list[str]: Encoded time string(s)
31
"""
32
33
@staticmethod
34
def breakdown(epochs):
35
"""
36
Break down CDF epochs into date/time components.
37
38
Parameters:
39
- epochs (int | float | complex | array-like): CDF epoch values of any type
40
41
Returns:
42
numpy.ndarray: Array with shape (..., 9) containing:
43
[year, month, day, hour, minute, second, millisecond,
44
microsecond, nanosecond] for each epoch
45
"""
46
47
@staticmethod
48
def to_datetime(cdf_time):
49
"""
50
Convert CDF time to numpy datetime64 array.
51
52
Parameters:
53
- cdf_time (int | float | complex | array-like): CDF epoch values
54
55
Returns:
56
numpy.ndarray[datetime64]: NumPy datetime64 array
57
"""
58
59
@staticmethod
60
def unixtime(cdf_time):
61
"""
62
Convert CDF time to Unix timestamp (seconds since 1970-01-01).
63
64
Parameters:
65
- cdf_time (int | float | complex | array-like): CDF epoch values
66
67
Returns:
68
float | numpy.ndarray: Unix timestamp(s)
69
"""
70
71
@staticmethod
72
def compute(datetimes):
73
"""
74
Auto-detect appropriate CDF epoch type and compute from date components.
75
76
Parameters:
77
- datetimes (array-like): Date/time components as nested lists/arrays
78
[[year, month, day, hour, min, sec, ms], ...]
79
80
Returns:
81
int | float | complex | numpy.ndarray: Appropriate CDF epoch type
82
"""
83
```
84
85
**Usage Examples:**
86
87
```python
88
import cdflib
89
90
# Auto-detect and encode different epoch types
91
epoch_float = 63731251200000.0 # CDF_EPOCH
92
epoch_tt2000 = 725846462184000000 # TT2000
93
epoch_16 = complex(63731251200, 0) # CDF_EPOCH16
94
95
# Encode to human-readable strings
96
print(cdflib.cdfepoch.encode(epoch_float)) # "01-Jan-2021 00:00:00.000"
97
print(cdflib.cdfepoch.encode(epoch_tt2000)) # "01-Jan-2023 00:01:02.184000000"
98
print(cdflib.cdfepoch.encode(epoch_16)) # "01-Jan-2021 00:00:00.000000000000"
99
100
# Break down to components
101
components = cdflib.cdfepoch.breakdown([epoch_float, epoch_tt2000])
102
print(components) # [[2021, 1, 1, 0, 0, 0, 0, 0, 0], [2023, 1, 1, 0, 1, 2, 184, 0, 0]]
103
104
# Convert to numpy datetime64
105
dt_array = cdflib.cdfepoch.to_datetime([epoch_float, epoch_tt2000])
106
print(dt_array) # ['2021-01-01T00:00:00.000' '2023-01-01T00:01:02.184']
107
108
# Convert to Unix timestamp
109
unix_times = cdflib.cdfepoch.unixtime([epoch_float, epoch_tt2000])
110
print(unix_times) # [1609459200.0, 1672531262.184]
111
```
112
113
### Unix Time Conversion
114
115
Convert Unix timestamps to different CDF epoch formats.
116
117
```python { .api }
118
@staticmethod
119
def timestamp_to_cdfepoch(unixtime_data):
120
"""
121
Convert Unix timestamp to CDF_EPOCH format.
122
123
Parameters:
124
- unixtime_data (float | array-like): Unix timestamp(s) in seconds
125
126
Returns:
127
numpy.ndarray: CDF_EPOCH values (milliseconds since Year 0)
128
"""
129
130
@staticmethod
131
def timestamp_to_cdfepoch16(unixtime_data):
132
"""
133
Convert Unix timestamp to CDF_EPOCH16 format.
134
135
Parameters:
136
- unixtime_data (float | array-like): Unix timestamp(s) in seconds
137
138
Returns:
139
numpy.ndarray: CDF_EPOCH16 values (picoseconds since Year 0)
140
"""
141
142
@staticmethod
143
def timestamp_to_tt2000(unixtime_data):
144
"""
145
Convert Unix timestamp to TT2000 format.
146
147
Parameters:
148
- unixtime_data (float | array-like): Unix timestamp(s) in seconds
149
150
Returns:
151
numpy.ndarray: TT2000 values (nanoseconds since J2000)
152
"""
153
```
154
155
**Usage Examples:**
156
157
```python
158
import cdflib
159
import time
160
161
# Current Unix timestamp
162
current_time = time.time() # e.g., 1672531262.184
163
164
# Convert to different CDF epoch formats
165
cdf_epoch = cdflib.cdfepoch.timestamp_to_cdfepoch(current_time)
166
cdf_epoch16 = cdflib.cdfepoch.timestamp_to_cdfepoch16(current_time)
167
tt2000 = cdflib.cdfepoch.timestamp_to_tt2000(current_time)
168
169
print(f"CDF_EPOCH: {cdf_epoch[0]}") # Milliseconds since Year 0
170
print(f"CDF_EPOCH16: {cdf_epoch16[0]}") # Complex number (picoseconds)
171
print(f"TT2000: {tt2000[0]}") # Nanoseconds since J2000
172
173
# Convert array of timestamps
174
timestamps = [1672531200.0, 1672531262.184, 1672531300.0]
175
epochs = cdflib.cdfepoch.timestamp_to_cdfepoch(timestamps)
176
print(f"Converted epochs: {epochs}")
177
```
178
179
### CDF_EPOCH Operations
180
181
Operations specific to CDF_EPOCH format (milliseconds since Year 0).
182
183
```python { .api }
184
@staticmethod
185
def encode_epoch(epochs, iso_8601=True):
186
"""
187
Encode CDF_EPOCH values to strings.
188
189
Parameters:
190
- epochs (float | array-like): CDF_EPOCH values
191
- iso_8601 (bool): Use ISO 8601 format if True
192
193
Returns:
194
str | list[str]: Encoded time string(s)
195
"""
196
197
@staticmethod
198
def compute_epoch(dates):
199
"""
200
Compute CDF_EPOCH from date/time components.
201
202
Parameters:
203
- dates (array-like): Date components as [year, month, day, hour, min, sec, ms]
204
or nested array for multiple dates
205
206
Returns:
207
float | numpy.ndarray: CDF_EPOCH value(s)
208
"""
209
210
@staticmethod
211
def breakdown_epoch(epochs):
212
"""
213
Break down CDF_EPOCH to date/time components.
214
215
Parameters:
216
- epochs (float | array-like): CDF_EPOCH values
217
218
Returns:
219
numpy.ndarray: Components [year, month, day, hour, min, sec, ms]
220
"""
221
222
@staticmethod
223
def epochrange_epoch(start_time, end_time, epochs):
224
"""
225
Find CDF_EPOCH values within a time range.
226
227
Parameters:
228
- start_time (float): Start CDF_EPOCH value
229
- end_time (float): End CDF_EPOCH value
230
- epochs (array-like): CDF_EPOCH array to search
231
232
Returns:
233
tuple: (indices, values) of epochs within range
234
"""
235
```
236
237
**Usage Examples:**
238
239
```python
240
import cdflib
241
242
# Compute CDF_EPOCH from date components
243
date_components = [2023, 6, 15, 14, 30, 45, 123]
244
epoch = cdflib.cdfepoch.compute_epoch(date_components)
245
print(f"CDF_EPOCH: {epoch}") # Single epoch value
246
247
# Multiple dates
248
dates = [
249
[2023, 1, 1, 0, 0, 0, 0],
250
[2023, 6, 15, 12, 0, 0, 0],
251
[2023, 12, 31, 23, 59, 59, 999]
252
]
253
epochs = cdflib.cdfepoch.compute_epoch(dates)
254
print(f"Multiple epochs: {epochs}")
255
256
# Encode to strings
257
time_strings = cdflib.cdfepoch.encode_epoch(epochs)
258
print(f"Time strings: {time_strings}")
259
260
# ISO 8601 format
261
iso_strings = cdflib.cdfepoch.encode_epoch(epochs, iso_8601=True)
262
print(f"ISO format: {iso_strings}")
263
264
# Break down to components
265
components = cdflib.cdfepoch.breakdown_epoch(epochs)
266
print(f"Components shape: {components.shape}") # (3, 7) for 3 epochs
267
268
# Find epochs within range
269
start_epoch = cdflib.cdfepoch.compute_epoch([2023, 3, 1, 0, 0, 0, 0])
270
end_epoch = cdflib.cdfepoch.compute_epoch([2023, 9, 1, 0, 0, 0, 0])
271
indices, values = cdflib.cdfepoch.epochrange_epoch(start_epoch, end_epoch, epochs)
272
print(f"Epochs in range: {values}")
273
```
274
275
### CDF_EPOCH16 Operations
276
277
Operations for CDF_EPOCH16 format (picoseconds since Year 0, highest precision).
278
279
```python { .api }
280
@staticmethod
281
def encode_epoch16(epochs, iso_8601=True):
282
"""
283
Encode CDF_EPOCH16 values to strings.
284
285
Parameters:
286
- epochs (complex | array-like): CDF_EPOCH16 values
287
- iso_8601 (bool): Use ISO 8601 format if True
288
289
Returns:
290
str | list[str]: Encoded time string(s) with picosecond precision
291
"""
292
293
@staticmethod
294
def compute_epoch16(datetimes):
295
"""
296
Compute CDF_EPOCH16 from date/time components.
297
298
Parameters:
299
- datetimes (array-like): Components [year, month, day, hour, min, sec, ms, us, ns, ps]
300
or nested array for multiple dates
301
302
Returns:
303
complex | numpy.ndarray: CDF_EPOCH16 value(s)
304
"""
305
306
@staticmethod
307
def breakdown_epoch16(epochs):
308
"""
309
Break down CDF_EPOCH16 to date/time components.
310
311
Parameters:
312
- epochs (complex | array-like): CDF_EPOCH16 values
313
314
Returns:
315
numpy.ndarray: Components [year, month, day, hour, min, sec, ms, us, ns, ps]
316
"""
317
318
@staticmethod
319
def epochrange_epoch16(start_time, end_time, epochs):
320
"""
321
Find CDF_EPOCH16 values within a time range.
322
323
Parameters:
324
- start_time (complex): Start CDF_EPOCH16 value
325
- end_time (complex): End CDF_EPOCH16 value
326
- epochs (array-like): CDF_EPOCH16 array to search
327
328
Returns:
329
tuple: (indices, values) of epochs within range
330
"""
331
```
332
333
### TT2000 Operations
334
335
Operations for TT2000 format (nanoseconds since J2000 with leap seconds).
336
337
```python { .api }
338
@staticmethod
339
def encode_tt2000(tt2000, iso_8601=True):
340
"""
341
Encode TT2000 values to strings.
342
343
Parameters:
344
- tt2000 (int | array-like): TT2000 values
345
- iso_8601 (bool): Use ISO 8601 format if True
346
347
Returns:
348
str | list[str]: Encoded time string(s) with nanosecond precision
349
"""
350
351
@staticmethod
352
def compute_tt2000(datetimes):
353
"""
354
Compute TT2000 from date/time components.
355
356
Parameters:
357
- datetimes (array-like): Components [year, month, day, hour, min, sec, ms, us, ns]
358
or nested array for multiple dates
359
360
Returns:
361
int | numpy.ndarray: TT2000 value(s)
362
"""
363
364
@staticmethod
365
def breakdown_tt2000(tt2000):
366
"""
367
Break down TT2000 to date/time components.
368
369
Parameters:
370
- tt2000 (int | array-like): TT2000 values
371
372
Returns:
373
numpy.ndarray: Components [year, month, day, hour, min, sec, ms, us, ns]
374
"""
375
376
@staticmethod
377
def epochrange_tt2000(start_time, end_time, tt2000):
378
"""
379
Find TT2000 values within a time range.
380
381
Parameters:
382
- start_time (int): Start TT2000 value
383
- end_time (int): End TT2000 value
384
- tt2000 (array-like): TT2000 array to search
385
386
Returns:
387
tuple: (indices, values) of TT2000 values within range
388
"""
389
```
390
391
**Usage Examples:**
392
393
```python
394
import cdflib
395
396
# TT2000 with nanosecond precision
397
date_with_ns = [2023, 6, 15, 14, 30, 45, 123, 456, 789]
398
tt2000_value = cdflib.cdfepoch.compute_tt2000(date_with_ns)
399
print(f"TT2000: {tt2000_value}")
400
401
# Encode with nanosecond precision
402
tt2000_string = cdflib.cdfepoch.encode_tt2000(tt2000_value)
403
print(f"TT2000 string: {tt2000_string}")
404
405
# CDF_EPOCH16 with picosecond precision
406
date_with_ps = [2023, 6, 15, 14, 30, 45, 123, 456, 789, 123]
407
epoch16_value = cdflib.cdfepoch.compute_epoch16(date_with_ps)
408
print(f"CDF_EPOCH16: {epoch16_value}")
409
410
# Break down TT2000
411
tt2000_components = cdflib.cdfepoch.breakdown_tt2000(tt2000_value)
412
print(f"TT2000 components: {tt2000_components}") # Includes nanosecond component
413
```
414
415
### Time Range Operations
416
417
Find epochs within specified time ranges for data filtering.
418
419
```python { .api }
420
@staticmethod
421
def findepochrange(start_time, end_time, epochs):
422
"""
423
Generic function to find epoch range regardless of format.
424
425
Parameters:
426
- start_time: Start time in same format as epochs
427
- end_time: End time in same format as epochs
428
- epochs (array-like): Epoch array to search
429
430
Returns:
431
tuple: (start_index, end_index) of range boundaries
432
"""
433
```
434
435
**Usage Example:**
436
437
```python
438
import cdflib
439
440
# Create sample epoch array
441
dates = [[2023, i, 1, 0, 0, 0, 0] for i in range(1, 13)] # Monthly data
442
epochs = cdflib.cdfepoch.compute_epoch(dates)
443
444
# Find summer months (June to August)
445
start_summer = cdflib.cdfepoch.compute_epoch([2023, 6, 1, 0, 0, 0, 0])
446
end_summer = cdflib.cdfepoch.compute_epoch([2023, 8, 31, 23, 59, 59, 999])
447
448
start_idx, end_idx = cdflib.cdfepoch.findepochrange(start_summer, end_summer, epochs)
449
summer_epochs = epochs[start_idx:end_idx+1]
450
summer_strings = cdflib.cdfepoch.encode_epoch(summer_epochs)
451
print(f"Summer months: {summer_strings}")
452
```
453
454
### String Parsing
455
456
Parse time strings back to date components.
457
458
```python { .api }
459
@staticmethod
460
def parse(value):
461
"""
462
Parse time strings into date/time components.
463
464
Parameters:
465
- value (str | tuple[str] | list[str]): Time string(s) to parse
466
467
Returns:
468
numpy.ndarray: Date/time components array
469
"""
470
```
471
472
**Usage Example:**
473
474
```python
475
import cdflib
476
477
# Parse various time string formats
478
time_strings = [
479
"2023-06-15T14:30:45.123",
480
"15-Jun-2023 14:30:45.123",
481
"2023-12-31T23:59:59.999"
482
]
483
484
parsed_dates = cdflib.cdfepoch.parse(time_strings)
485
print(f"Parsed components: {parsed_dates}")
486
487
# Convert parsed dates to epochs
488
epochs = cdflib.cdfepoch.compute_epoch(parsed_dates)
489
print(f"Computed epochs: {epochs}")
490
```
491
492
## Practical Examples
493
494
### Scientific Time Series Analysis
495
496
```python
497
import cdflib
498
import numpy as np
499
500
# Create hourly measurements for one day
501
base_date = [2023, 6, 15, 0, 0, 0, 0]
502
hourly_dates = [[2023, 6, 15, hour, 0, 0, 0] for hour in range(24)]
503
504
# Convert to different epoch formats for comparison
505
cdf_epochs = cdflib.cdfepoch.compute_epoch(hourly_dates)
506
tt2000_epochs = cdflib.cdfepoch.compute_tt2000(hourly_dates)
507
508
# Create synthetic temperature data
509
temperatures = 20 + 10 * np.sin(np.linspace(0, 2*np.pi, 24)) + np.random.normal(0, 1, 24)
510
511
# Find daytime hours (6 AM to 6 PM)
512
morning = cdflib.cdfepoch.compute_epoch([2023, 6, 15, 6, 0, 0, 0])
513
evening = cdflib.cdfepoch.compute_epoch([2023, 6, 15, 18, 0, 0, 0])
514
515
start_idx, end_idx = cdflib.cdfepoch.findepochrange(morning, evening, cdf_epochs)
516
daytime_temps = temperatures[start_idx:end_idx+1]
517
daytime_epochs = cdf_epochs[start_idx:end_idx+1]
518
519
print(f"Daytime temperature range: {np.min(daytime_temps):.1f} to {np.max(daytime_temps):.1f}°C")
520
print(f"Daytime period: {cdflib.cdfepoch.encode_epoch(daytime_epochs[0])} to {cdflib.cdfepoch.encode_epoch(daytime_epochs[-1])}")
521
```
522
523
### Time Format Interoperability
524
525
```python
526
import cdflib
527
import datetime
528
529
# Convert between different time representations
530
python_datetime = datetime.datetime(2023, 6, 15, 14, 30, 45, 123456)
531
532
# Convert to Unix timestamp
533
unix_time = python_datetime.timestamp()
534
535
# Convert Unix time to CDF formats
536
cdf_epoch = cdflib.cdfepoch.timestamp_to_cdfepoch(unix_time)[0]
537
tt2000 = cdflib.cdfepoch.timestamp_to_tt2000(unix_time)[0]
538
539
# Convert back to verify
540
unix_from_cdf = cdflib.cdfepoch.unixtime(cdf_epoch)
541
unix_from_tt2000 = cdflib.cdfepoch.unixtime(tt2000)
542
543
print(f"Original Unix time: {unix_time}")
544
print(f"From CDF_EPOCH: {unix_from_cdf}")
545
print(f"From TT2000: {unix_from_tt2000}")
546
print(f"Differences (microseconds): CDF={abs(unix_time-unix_from_cdf)*1e6:.1f}, TT2000={abs(unix_time-unix_from_tt2000)*1e6:.1f}")
547
548
# Display in human-readable format
549
print(f"CDF_EPOCH string: {cdflib.cdfepoch.encode_epoch(cdf_epoch)}")
550
print(f"TT2000 string: {cdflib.cdfepoch.encode_tt2000(tt2000)}")
551
```
552
553
## Types
554
555
```python { .api }
556
# Type aliases used in the epochs module
557
epoch_scalar_types = Union[int, np.int64, float, np.float64, complex, np.complex128]
558
epoch_list_types = Union[List[int], List[np.int64], List[float], List[np.float64],
559
List[complex], List[np.complex128]]
560
epoch_types = Union[epoch_scalar_types, epoch_list_types, numpy.ndarray]
561
562
cdf_epoch_type = Union[float, np.float64, List[float], numpy.ndarray]
563
cdf_epoch16_type = Union[complex, np.complex128, List[complex], numpy.ndarray]
564
cdf_tt2000_type = Union[int, np.int64, List[int], numpy.ndarray]
565
566
encoded_type = Union[str, List[str]]
567
```