Skip to content

cdfepoch¤

There are three (3) unique epoch data types in CDF: CDF_EPOCH, CDF_EPOCH16 and CDF_TIME_TT2000.

  • CDF_EPOCH is milliseconds since Year 0.
  • CDF_EPOCH16 is picoseconds since Year 0.
  • CDF_TIME_TT2000 (TT2000 as short) is nanoseconds since J2000 with leap seconds.

The following two classes contain functions to convert those times into formats that are in more standard use.

epochs ¤

Classes:

Name Description
CDFepoch

Convert between CDF-based epochs, np.datetime64, and Unix time.

CDFepoch ¤

Convert between CDF-based epochs, np.datetime64, and Unix time.

There are three (3) epoch data types in CDF: 1. CDF_EPOCH is milliseconds since Year 0 represented as a single double (float in Python), 2. CDF_EPOCH16 is picoseconds since Year 0 represented as 2-doubles (complex in Python), and 3. CDF_TIME_TT2000 (TT2000 as short) is nanoseconds since J2000 with leap seconds, represented by an 8-byte integer (int in Python).

In Numpy, they are np.float64, np.complex128 and np.int64, respectively. All these epoch values can come from from CDF.varget function.

Example
>>> import cdflib
>>> # Convert to an epoch
>>> epoch = cdflib.cdfepoch.compute_epoch([2017,1,1,1,1,1,111])
>>> # Convert from an epoch
>>> time = cdflib.cdfepoch.to_datetime(epoch)  # Or pass epochs via CDF.varget.

Methods:

Name Description
breakdown

Returns

breakdown_epoch

Calculate date and time from epochs

breakdown_epoch16

Calculate date and time from epochs

breakdown_tt2000

Breaks down the epoch(s) into UTC components.

compute

Computes the provided date/time components into CDF epoch value(s).

encode

Converts one or more epochs into UTC strings. The input epoch

findepochrange

Finds the record range within the start and end time from values

parse

Parses the provided date/time string(s) into CDF epoch value(s).

timestamp_to_cdfepoch

Converts a unix timestamp to CDF_EPOCH, the number of milliseconds since the year 0.

timestamp_to_cdfepoch16

Converts a unix timestamp to CDF_EPOCH16

timestamp_to_tt2000

Converts a unix timestamp to CDF_TIME_TT2000

to_datetime

Converts CDF epoch argument to numpy.datetime64.

unixtime

Converts CDF epoch argument into seconds after 1970-01-01. This method

breakdown staticmethod ¤

breakdown(epochs: epoch_types) -> ndarray

Returns:

Type Description
ndarray

1D if scalar input, 2D otherwise.

Source code in cdflib/epochs.py
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
@staticmethod
def breakdown(epochs: epoch_types) -> np.ndarray:
    """
    Returns
    -------
    np.ndarray
        1D if scalar input, 2D otherwise.
    """
    epochs = np.array(epochs)
    if epochs.dtype.type == np.int64:  # type: ignore
        return CDFepoch.breakdown_tt2000(epochs)
    elif epochs.dtype.type == np.float64:  # type: ignore
        return CDFepoch.breakdown_epoch(epochs)
    elif epochs.dtype.type == np.complex128:  # type: ignore
        return CDFepoch.breakdown_epoch16(epochs)
    else:
        raise TypeError(f"Not sure how to handle type {epochs.dtype}")

breakdown_epoch staticmethod ¤

breakdown_epoch(epochs: cdf_epoch_type) -> ndarray

Calculate date and time from epochs

Parameters:

Name Type Description Default

epochs ¤

int, float, or array-like

Single, list, tuple, or np.array of epoch values

required

Returns:

Name Type Description
components list

List or array of date and time values. The last axis contains (in order): year, month, day, hour, minute, second, and millisecond

Notes

If a bad epoch (-1.0e31) is supplied, a fill date of 9999-12-31 23:59:59 and 999 ms is returned.

Source code in cdflib/epochs.py
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
@staticmethod
def breakdown_epoch(epochs: cdf_epoch_type) -> np.ndarray:
    """Calculate date and time from epochs

    Parameters
    ----------
    epochs : int, float, or array-like
        Single, list, tuple, or np.array of epoch values

    Returns
    -------
    components : list
        List or array of date and time values.  The last axis contains
        (in order): year, month, day, hour, minute, second, and millisecond

    Notes
    -----
    If a bad epoch (-1.0e31) is supplied, a fill date of
    9999-12-31 23:59:59 and 999 ms is returned.

    """
    # Test input and cast it as an array of floats
    if (
        isinstance(epochs, float)
        or isinstance(epochs, np.float64)
        or isinstance(epochs, list)
        or isinstance(epochs, tuple)
        or isinstance(epochs, np.ndarray)
        or isinstance(epochs, int)
    ):
        new_epochs = np.asarray(epochs).astype(float)
        if new_epochs.shape == ():
            cshape: list[cdf_epoch_type] = []
            new_epochs = np.array([epochs], dtype=float)
        else:
            cshape = list(new_epochs.shape)
    else:
        raise TypeError("Bad data for epochs: {:}".format(type(epochs)))

    # Initialize output to default values
    cshape.append(7)
    components = np.full(shape=cshape, fill_value=[9999, 12, 31, 23, 59, 59, 999])  # type: ignore
    for i, epoch in enumerate(new_epochs):
        # Ignore fill values and NaNs
        if (epoch != -1.0e31) and not np.isnan(epoch):
            esec = -epoch / 1000.0 if epoch < 0.0 else epoch / 1000.0
            date_time = CDFepoch._calc_from_julian(esec, 0.0)

            ms = (epoch % 1000.0).astype(int)
            date_time[..., 6] = int(ms) if ms.shape == () else ms

            if len(components.shape) == 1:
                components = date_time[..., :7]
            else:
                components[i] = date_time[..., :7]
        elif epoch == 0:
            components[i] = [0, 1, 1, 0, 0, 0, 0]

    return np.squeeze(components)

breakdown_epoch16 staticmethod ¤

breakdown_epoch16(epochs: cdf_epoch16_type) -> NDArray

Calculate date and time from epochs

Parameters:

Name Type Description Default

epochs ¤

array - like

Single, list, tuple, or np.array of epoch values

required

Returns:

Name Type Description
components ndarray

List or array of date and time values. The last axis contains (in order): year, month, day, hour, minute, second, millisecond, microsecond, nanosecond, and picosecond

Notes

If a bad epoch (-1.0e31 for the real and imaginary components) is supplied, a fill date of 9999-12-31 23:59:59 and 999 ms, 999 us, 999 ns, and 999 ps is returned

Source code in cdflib/epochs.py
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
@staticmethod
def breakdown_epoch16(epochs: cdf_epoch16_type) -> npt.NDArray:
    """
    Calculate date and time from epochs

    Parameters
    ----------
    epochs : array-like
        Single, list, tuple, or np.array of epoch values

    Returns
    -------
    components : ndarray
        List or array of date and time values.  The last axis contains
        (in order): year, month, day, hour, minute, second, millisecond,
        microsecond, nanosecond, and picosecond

    Notes
    -----
    If a bad epoch (-1.0e31 for the real and imaginary components) is
    supplied, a fill date of 9999-12-31 23:59:59 and 999 ms, 999 us,
    999 ns, and 999 ps is returned

    """

    if isinstance(epochs, (complex, np.complex128)) or isinstance(epochs, (list, tuple, np.ndarray)):
        new_epochs = np.asarray(epochs)
        if new_epochs.shape == ():
            cshape: list[cdf_epoch16_type] = []
            new_epochs = np.array([epochs])
        else:
            cshape = list(new_epochs.shape)
    else:
        raise TypeError("Bad data for epochs: {:}".format(type(epochs)))

    cshape.append(10)
    components = np.full(shape=cshape, fill_value=[9999, 12, 31, 23, 59, 59, 999, 999, 999, 999])  # type: ignore
    for i, epoch16 in enumerate(new_epochs):
        # Ignore fill values
        if (epoch16.real != -1.0e31) or (epoch16.imag != -1.0e31) or np.isnan(epoch16):
            if (epoch16.imag == -1.0e30) or (epoch16.imag == -1.0e30):
                components[i] = [0, 1, 1, 0, 0, 0, 0, 0, 0, 0]
                continue
            esec = -epoch16.real if epoch16.real < 0.0 else epoch16.real
            efra = -epoch16.imag if epoch16.imag < 0.0 else epoch16.imag

            if len(components.shape) == 1:
                components = CDFepoch._calc_from_julian(esec, efra)
            else:
                components[i] = CDFepoch._calc_from_julian(esec, efra)

    return components

breakdown_tt2000 staticmethod ¤

breakdown_tt2000(tt2000: cdf_tt2000_type) -> ndarray

Breaks down the epoch(s) into UTC components.

Calculate date and time from cdf_time_tt2000 integers

Parameters:

Name Type Description Default

tt2000 ¤

array - like

Single, list, tuple, or np.array of tt2000 values

required

Returns:

Name Type Description
components ndarray

List or array of date and time values. The last axis contains (in order): year, month, day, hour, minute, second, millisecond, microsecond, and nanosecond

Notes

If a bad epoch is supplied, a fill date of 9999-12-31 23:59:59 and 999 ms, 999 us, and 999 ns is returned.

Source code in cdflib/epochs.py
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
@staticmethod
def breakdown_tt2000(tt2000: cdf_tt2000_type) -> np.ndarray:
    """
    Breaks down the epoch(s) into UTC components.

    Calculate date and time from cdf_time_tt2000 integers

    Parameters
    ----------
    tt2000 : array-like
        Single, list, tuple, or np.array of tt2000 values

    Returns
    -------
    components : ndarray
        List or array of date and time values.  The last axis contains
        (in order): year, month, day, hour, minute, second, millisecond,
        microsecond, and nanosecond

    Notes
    -----
    If a bad epoch is supplied, a fill date of 9999-12-31 23:59:59 and 999 ms, 999 us, and
    999 ns is returned.
    """

    new_tt2000 = np.atleast_1d(tt2000).astype(np.int64)
    count = len(new_tt2000)
    toutcs = np.zeros((9, count), dtype=int)
    datxs = CDFepoch._LeapSecondsfromJ2000(new_tt2000)

    # Do some computations on arrays to speed things up
    post2000 = new_tt2000 > 0
    nanoSecsSinceJ2000 = new_tt2000.copy()
    nanoSecsSinceJ2000[~post2000] += CDFepoch.T12hinNanoSecs
    nanoSecsSinceJ2000[~post2000] -= CDFepoch.dTinNanoSecs

    secsSinceJ2000 = (nanoSecsSinceJ2000 / CDFepoch.SECinNanoSecsD).astype(np.int64)
    nansecs = (nanoSecsSinceJ2000 - (secsSinceJ2000 * CDFepoch.SECinNanoSecs)).astype(np.int64)  # type: ignore

    posNanoSecs = new_tt2000 > 0
    secsSinceJ2000[posNanoSecs] -= 32
    secsSinceJ2000[posNanoSecs] += 43200
    nansecs[posNanoSecs] -= 184000000

    negNanoSecs = nansecs < 0
    nansecs[negNanoSecs] += CDFepoch.SECinNanoSecs
    secsSinceJ2000[negNanoSecs] -= 1

    t2s = secsSinceJ2000 * CDFepoch.SECinNanoSecs + nansecs

    post72: np.ndarray = datxs[:, 0] > 0
    secsSinceJ2000[post72] -= datxs[post72, 0].astype(int)
    epochs = CDFepoch.J2000Since0AD12hSec + secsSinceJ2000

    datxzero = datxs[:, 1] == 0.0
    epochs[post72 & ~datxzero] -= 1
    xdates = CDFepoch._EPOCHbreakdownTT2000(epochs)

    # If 1 second was subtracted, add 1 second back in
    # Be careful not to go 60 or above
    xdates[5, post72 & ~datxzero] += 1
    xdates[4, post72 & ~datxzero] += np.floor(xdates[5, post72 & ~datxzero] / 60.0)
    xdates[5, post72 & ~datxzero] = xdates[5, post72 & ~datxzero] % 60

    # Set toutcs, then loop through and correct for pre-1972
    toutcs[:6, :] = xdates[:6, :]

    for x in np.nonzero(~post72)[0]:
        if datxs[x, 0] <= 0.0:
            # pre-1972...
            epoch = epochs[x]
            t2 = t2s[x]
            t3 = new_tt2000[x]
            nansec = nansecs[x]

            xdate = np.zeros(9)
            xdate[:6] = xdates[:, x]
            xdate[8] = nansec

            tmpNanosecs = CDFepoch.compute_tt2000(xdate)
            if tmpNanosecs != t3:
                dat0 = CDFepoch._LeapSecondsfromYMD(xdate[0], xdate[1], xdate[2])
                tmpx = t2 - int(dat0 * CDFepoch.SECinNanoSecs)
                tmpy = int(float(tmpx / CDFepoch.SECinNanoSecsD))
                nansec = int(tmpx - tmpy * CDFepoch.SECinNanoSecs)
            if nansec < 0:
                nansec = CDFepoch.SECinNanoSecs + nansec
                tmpy = tmpy - 1
                epoch = tmpy + CDFepoch.J2000Since0AD12hSec
                xdate = np.zeros(9)
                xdate[:6] = CDFepoch._EPOCHbreakdownTT2000(epoch)[:, 0]
                xdate[8] = nansec
                tmpNanosecs = CDFepoch.compute_tt2000(xdate)
            if tmpNanosecs != t3:
                dat0 = CDFepoch._LeapSecondsfromYMD(xdate[0], xdate[1], xdate[2])
                tmpx = t2 - int(dat0 * CDFepoch.SECinNanoSecs)
                tmpy = int((1.0 * tmpx) / CDFepoch.SECinNanoSecsD)
                nansec = int(tmpx - tmpy * CDFepoch.SECinNanoSecs)
                if nansec < 0:
                    nansec = CDFepoch.SECinNanoSecs + nansec
                    tmpy = tmpy - 1
                epoch = tmpy + CDFepoch.J2000Since0AD12hSec
                xdate = np.zeros(9)
                xdate[:6] = CDFepoch._EPOCHbreakdownTT2000(epoch)[:, 0]
                xdate[8] = nansec
                tmpNanosecs = CDFepoch.compute_tt2000(xdate)
                if tmpNanosecs != t3:
                    dat0 = CDFepoch._LeapSecondsfromYMD(xdate[0], xdate[1], xdate[2])
                    tmpx = t2 - int(dat0 * CDFepoch.SECinNanoSecs)
                    tmpy = int((1.0 * tmpx) / CDFepoch.SECinNanoSecsD)
                    nansec = int(tmpx - tmpy * CDFepoch.SECinNanoSecs)
                    if nansec < 0:
                        nansec = CDFepoch.SECinNanoSecs + nansec
                        tmpy = tmpy - 1
                    epoch = tmpy + CDFepoch.J2000Since0AD12hSec
                    # One more determination
                    xdate = CDFepoch._EPOCHbreakdownTT2000(epoch).ravel()
            nansecs[x] = nansec
            toutcs[:6, x] = xdate[:6]

    # Finished pre-1972 correction
    ml1 = nansecs // 1000000
    tmp1 = nansecs - (1000000 * ml1)

    overflow = ml1 > 1000
    ml1[overflow] -= 1000
    toutcs[6, :] = ml1
    toutcs[5, overflow] += 1

    ma1 = tmp1 // 1000
    na1 = tmp1 - 1000 * ma1
    toutcs[7, :] = ma1
    toutcs[8, :] = na1

    # Check standard fill and pad values
    cdf_epoch_time_tt2000 = np.atleast_2d(toutcs.T)
    fillval_locations = np.all(cdf_epoch_time_tt2000 == [1707, 9, 22, 12, 12, 10, 961, 224, 192], axis=1)
    cdf_epoch_time_tt2000[fillval_locations] = [9999, 12, 31, 23, 59, 59, 999, 999, 999]
    padval_locations = np.all(cdf_epoch_time_tt2000 == [1707, 9, 22, 12, 12, 10, 961, 224, 193], axis=1)
    cdf_epoch_time_tt2000[padval_locations] = [0, 1, 1, 0, 0, 0, 0, 0, 0]

    return np.squeeze(cdf_epoch_time_tt2000)

compute staticmethod ¤

compute(datetimes: ArrayLike) -> Union[int, float, complex, NDArray]

Computes the provided date/time components into CDF epoch value(s).

For CDF_EPOCH: For computing into CDF_EPOCH value, each date/time elements should have exactly seven (7) components, as year, month, day, hour, minute, second and millisecond, in a list. For example: [[2017,1,1,1,1,1,111],[2017,2,2,2,2,2,222]] Or, call function compute_epoch directly, instead, with at least three (3) first (up to seven) components. The last component, if not the 7th, can be a float that can have a fraction of the unit.

For CDF_EPOCH16: They should have exactly ten (10) components, as year, month, day, hour, minute, second, millisecond, microsecond, nanosecond and picosecond, in a list. For example: [[2017,1,1,1,1,1,123,456,789,999],[2017,2,2,2,2,2,987,654,321,999]] Or, call function compute_epoch directly, instead, with at least three (3) first (up to ten) components. The last component, if not the 10th, can be a float that can have a fraction of the unit.

For TT2000: Each TT2000 typed date/time should have exactly nine (9) components, as year, month, day, hour, minute, second, millisecond, microsecond, and nanosecond, in a list. For example: [[2017,1,1,1,1,1,123,456,789],[2017,2,2,2,2,2,987,654,321]] Or, call function compute_tt2000 directly, instead, with at least three (3) first (up to nine) components. The last component, if not the 9th, can be a float that can have a fraction of the unit.

Source code in cdflib/epochs.py
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
@staticmethod
def compute(datetimes: npt.ArrayLike) -> Union[int, float, complex, npt.NDArray]:
    """
    Computes the provided date/time components into CDF epoch value(s).

    For CDF_EPOCH:
        For computing into CDF_EPOCH value, each date/time elements should
        have exactly seven (7) components, as year, month, day, hour, minute,
        second and millisecond, in a list. For example:
        [[2017,1,1,1,1,1,111],[2017,2,2,2,2,2,222]]
        Or, call function compute_epoch directly, instead, with at least three
        (3) first (up to seven) components. The last component, if
        not the 7th, can be a float that can have a fraction of the unit.

    For CDF_EPOCH16:
        They should have exactly ten (10) components, as year,
        month, day, hour, minute, second, millisecond, microsecond, nanosecond
        and picosecond, in a list. For example:
        [[2017,1,1,1,1,1,123,456,789,999],[2017,2,2,2,2,2,987,654,321,999]]
        Or, call function compute_epoch directly, instead, with at least three
        (3) first (up to ten) components. The last component, if
        not the 10th, can be a float that can have a fraction of the unit.

    For TT2000:
        Each TT2000 typed date/time should have exactly nine (9) components, as
        year, month, day, hour, minute, second, millisecond, microsecond,
        and nanosecond, in a list.  For example:
        [[2017,1,1,1,1,1,123,456,789],[2017,2,2,2,2,2,987,654,321]]
        Or, call function compute_tt2000 directly, instead, with at least three
        (3) first (up to nine) components. The last component, if
        not the 9th, can be a float that can have a fraction of the unit.
    """

    if not isinstance(datetimes, (list, tuple, np.ndarray)):
        raise TypeError("datetime must be in list form")

    datetimes = np.atleast_2d(datetimes)
    items = datetimes.shape[1]  # type: ignore

    if items == 7:
        return _squeeze_or_scalar_real(CDFepoch.compute_epoch(datetimes))
    elif items == 10:
        return _squeeze_or_scalar_complex(CDFepoch.compute_epoch16(datetimes))
    elif items == 9:
        return _squeeze_or_scalar_real(CDFepoch.compute_tt2000(datetimes))
    else:
        raise TypeError("Unknown input")

encode staticmethod ¤

encode(epochs: epoch_types, iso_8601: bool = True) -> encoded_type

Converts one or more epochs into UTC strings. The input epoch format is deduced from the argument type.

Parameters:

Name Type Description Default

epochs ¤

epoch_types

One or more ECD epochs in one of three formats: 1. CDF_EPOCH: The input should be either a float or list of floats (in numpy, a np.float64 or a np.ndarray of np.float64) 2. CDF_EPOCH16: The input should be either a complex or list of complex(in numpy, a np.complex128 or a np.ndarray of np.complex128) 3. TT2000: The input should be either a int or list of ints (in numpy, a np.int64 or a np.ndarray of np.int64)

required

iso_8601 ¤

bool
The return time format. If ISO 8601 is True, the format is,
for example, 2008-02-02T06:08:10.10.012014016, otherwise
the format is 02-Feb-2008 06:08:10.012.014.016.
True
Source code in cdflib/epochs.py
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
@staticmethod
def encode(epochs: epoch_types, iso_8601: bool = True) -> encoded_type:
    """
    Converts one or more epochs into UTC strings. The input epoch
    format is deduced from the argument type.

    Parameters
    ----------
    epochs: int, float, list, complex
        One or more ECD epochs in one of three formats:
        1. CDF_EPOCH: The input should be either a float or list of floats
        (in numpy, a np.float64 or a np.ndarray of np.float64)
        2. CDF_EPOCH16: The input should be either a complex or list of
        complex(in numpy, a np.complex128 or a np.ndarray of np.complex128)
        3. TT2000: The input should be either a int or list of ints
        (in numpy, a np.int64 or a np.ndarray of np.int64)

    iso_8601: bool
            The return time format. If ISO 8601 is True, the format is,
            for example, 2008-02-02T06:08:10.10.012014016, otherwise
            the format is 02-Feb-2008 06:08:10.012.014.016.

    """
    epochs = np.array(epochs)
    if epochs.dtype == np.int64:
        return CDFepoch.encode_tt2000(epochs, iso_8601)
    elif epochs.dtype == np.float64:
        return CDFepoch.encode_epoch(epochs, iso_8601)
    elif epochs.dtype == np.complex128:
        return CDFepoch.encode_epoch16(epochs, iso_8601)
    else:
        raise TypeError(f"Not sure how to handle type {epochs.dtype}")

findepochrange staticmethod ¤

findepochrange(epochs: epochs_type, starttime: Optional[epoch_types] = None, endtime: Optional[epoch_types] = None) -> ndarray

Finds the record range within the start and end time from values of a CDF epoch data type. It returns a list of record numbers. If the start time is not provided, then it is assumed to be the minimum possible value. If the end time is not provided, then the maximum possible value is assumed. The epoch is assumed to be in the chronological order. The start and end times should have the proper number of date/time components, corresponding to the epoch's data type.

The start/end times should be in either be in epoch units, or in the list format described in "compute_epoch/epoch16/tt2000" section.

Source code in cdflib/epochs.py
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
@staticmethod
def findepochrange(
    epochs: epochs_type, starttime: Optional[epoch_types] = None, endtime: Optional[epoch_types] = None
) -> np.ndarray:
    """
    Finds the record range within the start and end time from values
    of a CDF epoch data type. It returns a list of record numbers.
    If the start time is not provided, then it is
    assumed to be the minimum possible value. If the end time is not
    provided, then the maximum possible value is assumed. The epoch is
    assumed to be in the chronological order. The start and end times
    should have the proper number of date/time components, corresponding
    to the epoch's data type.

    The start/end times should be in either be in epoch units, or in the list
    format described in "compute_epoch/epoch16/tt2000" section.
    """
    epochs = np.array(epochs)
    if epochs.dtype == np.int64:
        return CDFepoch.epochrange_tt2000(epochs, starttime, endtime)
    elif epochs.dtype == np.float64:
        return CDFepoch.epochrange_epoch(epochs, starttime, endtime)
    elif epochs.dtype == np.complex128:
        return CDFepoch.epochrange_epoch16(epochs, starttime, endtime)
    else:
        raise TypeError("Bad input")

parse staticmethod ¤

parse(value: Union[str, Tuple[str, ...], List[str]]) -> ndarray

Parses the provided date/time string(s) into CDF epoch value(s).

For CDF_EPOCH: The string has to be in the form of 'dd-mmm-yyyy hh🇲🇲ss.xxx' or 'yyyy-mm-ddThh🇲🇲ss.xxx' (in iso_8601). The string is the output from encode function.

For CDF_EPOCH16: The string has to be in the form of 'dd-mmm-yyyy hh🇲🇲ss.mmm.uuu.nnn.ppp' or 'yyyy-mm-ddThh🇲🇲ss.mmmuuunnnppp' (in iso_8601). The string is the output from encode function.

For TT2000: The string has to be in the form of 'dd-mmm-yyyy hh🇲🇲ss.mmm.uuu.nnn' or 'yyyy-mm-ddThh🇲🇲ss.mmmuuunnn' (in iso_8601). The string is the output from encode function.

Source code in cdflib/epochs.py
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
@staticmethod
def parse(value: Union[str, Tuple[str, ...], List[str]]) -> np.ndarray:
    """
    Parses the provided date/time string(s) into CDF epoch value(s).

    For CDF_EPOCH:
        The string has to be in the form of 'dd-mmm-yyyy hh:mm:ss.xxx' or
        'yyyy-mm-ddThh:mm:ss.xxx' (in iso_8601). The string is the output
        from encode function.

    For CDF_EPOCH16:
        The string has to be in the form of
        'dd-mmm-yyyy hh:mm:ss.mmm.uuu.nnn.ppp' or
        'yyyy-mm-ddThh:mm:ss.mmmuuunnnppp' (in iso_8601). The string is
        the output from encode function.

    For TT2000:
        The string has to be in the form of
        'dd-mmm-yyyy hh:mm:ss.mmm.uuu.nnn' or
        'yyyy-mm-ddThh:mm:ss.mmmuuunnn' (in iso_8601). The string is
        the output from encode function.
    """
    if isinstance(value, (list, tuple)) and not isinstance(value[0], str):
        raise TypeError("should be a string or a list of string")

    elif not isinstance(value, (list, tuple, str)):
        raise TypeError("Invalid value... should be a string or a list of string")
    else:
        if isinstance(value, (list, tuple)):
            num = len(value)
            epochs = []
            for x in range(num):
                epochs.append(CDFepoch._parse_epoch(value[x]))
            return np.squeeze(epochs)
        else:
            return np.squeeze(CDFepoch._parse_epoch(value))

timestamp_to_cdfepoch staticmethod ¤

timestamp_to_cdfepoch(unixtime_data: ArrayLike) -> ndarray

Converts a unix timestamp to CDF_EPOCH, the number of milliseconds since the year 0.

Source code in cdflib/epochs.py
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
@staticmethod
def timestamp_to_cdfepoch(unixtime_data: npt.ArrayLike) -> np.ndarray:
    """
    Converts a unix timestamp to CDF_EPOCH, the number of milliseconds since the year 0.
    """
    # Make sure the object is iterable.  Sometimes numpy arrays claim to be iterable when they aren't.
    times = np.atleast_1d(unixtime_data)

    cdf_time_data = []
    for ud in times:
        if not np.isnan(ud):
            dt = np.datetime64(int(ud * 1000), "ms")
            dt_item: datetime.datetime = dt.item()
            dt_to_convert = [
                dt_item.year,
                dt_item.month,
                dt_item.day,
                dt_item.hour,
                dt_item.minute,
                dt_item.second,
                int(dt_item.microsecond / 1000),
            ]
            converted_data = CDFepoch.compute(dt_to_convert)
        else:
            converted_data = np.nan
        cdf_time_data.append(converted_data)

    return np.array(cdf_time_data)

timestamp_to_cdfepoch16 staticmethod ¤

timestamp_to_cdfepoch16(unixtime_data: ArrayLike) -> ndarray

Converts a unix timestamp to CDF_EPOCH16

Source code in cdflib/epochs.py
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
@staticmethod
def timestamp_to_cdfepoch16(unixtime_data: npt.ArrayLike) -> np.ndarray:
    """
    Converts a unix timestamp to CDF_EPOCH16
    """
    # Make sure the object is iterable.  Sometimes numpy arrays claim to be iterable when they aren't.
    times = np.atleast_1d(unixtime_data)

    cdf_time_data = []
    for ud in times:
        if not np.isnan(ud):
            dt = np.datetime64(int(ud * 1000000), "us")
            dt_item: datetime.datetime = dt.item()
            dt_to_convert = [
                dt_item.year,
                dt_item.month,
                dt_item.day,
                dt_item.hour,
                dt_item.minute,
                dt_item.second,
                int(dt_item.microsecond / 1000),
                int(dt_item.microsecond % 1000),
                0,
                0,
            ]
            converted_data = CDFepoch.compute(dt_to_convert)
        else:
            converted_data = np.nan
        cdf_time_data.append(converted_data)

    return np.array(cdf_time_data)

timestamp_to_tt2000 staticmethod ¤

timestamp_to_tt2000(unixtime_data: ArrayLike) -> ndarray

Converts a unix timestamp to CDF_TIME_TT2000

Source code in cdflib/epochs.py
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
@staticmethod
def timestamp_to_tt2000(unixtime_data: npt.ArrayLike) -> np.ndarray:
    """
    Converts a unix timestamp to CDF_TIME_TT2000
    """
    # Make sure the object is iterable.  Sometimes numpy arrays claim to be iterable when they aren't.
    times = np.atleast_1d(unixtime_data)

    cdf_time_data = []
    for ud in times:
        if not np.isnan(ud):
            dt = np.datetime64(int(ud * 1000000), "us")
            dt_item: datetime.datetime = dt.item()
            dt_to_convert = [
                dt_item.year,
                dt_item.month,
                dt_item.day,
                dt_item.hour,
                dt_item.minute,
                dt_item.second,
                int(dt_item.microsecond / 1000),
                int(dt_item.microsecond % 1000),
                0,
            ]
            converted_data = CDFepoch.compute(dt_to_convert)
        else:
            converted_data = np.nan
        cdf_time_data.append(converted_data)

    return np.array(cdf_time_data)

to_datetime classmethod ¤

to_datetime(cdf_time: epoch_types) -> NDArray[datetime64]

Converts CDF epoch argument to numpy.datetime64.

Parameters: cdf_time: NumPy scalar/arrays to convert. np.int64 will be converted to cdf_tt2000, np.complex128 will be converted to cdf_epoch16, and floats will be converted to cdf_epoch.

Notes: Because of datetime64 limitations, CDF_EPOCH16 precision is only kept to the nearest nanosecond.

Source code in cdflib/epochs.py
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
@classmethod
def to_datetime(cls, cdf_time: epoch_types) -> npt.NDArray[np.datetime64]:
    """
    Converts CDF epoch argument to numpy.datetime64.

    Parameters:
        cdf_time: NumPy scalar/arrays to convert. np.int64 will be converted to cdf_tt2000, np.complex128 will be converted to cdf_epoch16, and floats will be converted to cdf_epoch.

    Notes:
        Because of datetime64 limitations, CDF_EPOCH16 precision is only kept to the nearest nanosecond.

    """
    times = cls.breakdown(cdf_time)
    times = np.atleast_2d(times)

    fillval_locations = np.all((times[:, 0:7] == [9999, 12, 31, 23, 59, 59, 999]), axis=1)
    padval_locations = np.all((times[:, 0:7] == [0, 1, 1, 0, 0, 0, 0]), axis=1)
    nan_locations = np.logical_or(fillval_locations, padval_locations)
    return cls._compose_date(nan_locations, *times.T[:9]).astype("datetime64[ns]")

unixtime staticmethod ¤

unixtime(cdf_time: ArrayLike) -> Union[float, NDArray]

Converts CDF epoch argument into seconds after 1970-01-01. This method converts a scalar, or array-like. Precision is only kept to the nearest microsecond.

Source code in cdflib/epochs.py
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
@staticmethod
def unixtime(cdf_time: npt.ArrayLike) -> Union[float, npt.NDArray]:
    """
    Converts CDF epoch argument into seconds after 1970-01-01. This method
    converts a scalar, or array-like. Precision is only kept to the
    nearest microsecond.
    """
    cdf_time = np.atleast_1d(cdf_time)
    time_list = np.atleast_2d(CDFepoch.breakdown(cdf_time))

    unixtime = []
    utc = datetime.timezone(datetime.timedelta())
    for t in time_list:
        date: List[int] = [0] * 7
        for i in range(0, len(t)):
            if i > 7:
                continue
            elif i == 6:
                date[i] = 1000 * t[i]
            elif i == 7:
                date[i - 1] += t[i]
            else:
                date[i] = t[i]
        unixtime.append(
            datetime.datetime(date[0], date[1], date[2], date[3], date[4], date[5], date[6], tzinfo=utc).timestamp()
        )
    return _squeeze_or_scalar_real(unixtime)