Source code for irfpy.spice.timescale

""" Information about conversion between timescales.

**3. Time scales**

- https://www.stjarnhimlen.se/comp/time.html
- https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/req/time.html

There are several definitions in time scales.
The page https://www.stjarnhimlen.se/comp/time.html summarizes in a good way.

===== ===== ===========================================================================================================================================
Scale SPICE Note
----- ----- -------------------------------------------------------------------------------------------------------------------------------------------
TAI   Y     Based upon the atomic second as defined by the ``oscillation of the undisturbed cesium atom
UTC   Y     Most frequently used time.  ``irfpy`` is based on.  UTC-TAI should be integer nubmer of seconds
UT          (Ambiguous due to multiple definition of UT? maximum difference <0.03s in between)
UT0         Raw, uncrrected UT.
UT1         UT0 corrected for polar wandering. *Usually UT means UT1*
UT2         UT1 corrected for seasonal variations in the Earth's rotatioanl speed.  It is considered obsolete
ET    Y     Ephemeris time, used 1960-83. Replaced in 1984 by TDT and TDB.
TDT   Y     Terrertrial Dynamical Time. Used 1984-2000.  TDT=TAI+32.184. Replaced by TT in 2001. Timescale of ephemerides from the Earth's surface.
TDB   Y=ET  Barycentric Dynamical Time.  Time scale of ephemeroids referred to the baricentre of the solar system. Diff from TDT a few mill-sec.
TT          Terrestrial time. Replacing TDT/TDB in 2001.  Practically, it can be the same as TDT (and thus ET and TDB)
TCG
TCB
===== ===== ===========================================================================================================================================

Practically, the relation ET=TDT=TDB=TT can be used.

::

                                                     ET 1960-1983
                                                    TDT 1984-2000
     UTC 1972-  GPS 1980-    TAI 1958-               TT 2001-
    ----+---------+-------------+-------------------------+-----
        |         |             |                         |
        |<------ TAI-UTC ------>|<-----   TT-TAI    ----->|
        |         |             |      32.184s fixed      |
        |<GPS-UTC>|<- TAI-GPS ->|                         |
        |         |  19s fixed  |                         |
        |                                                 |
        <> delta-UT = UT1-UTC                             |
         | (max 0.9 sec)                                  |
    -----+------------------------------------------------+-----
         |<-------------- delta-T = TT-UT1 -------------->|
        UT1 (UT)                                       TT/TDT/ET

In SPICE, you can use ``unitim`` function to convert between systems.
In addition, ``str2et`` can be used to convert ``datetime`` object to ``et``.

>>> import datetime
>>> t0_utc = datetime.datetime(2019, 1, 5, 12, 35, 40)
>>> print(t0_utc)
2019-01-05 12:35:40

>>> import spiceypy as spice

>>> from irfpy.spice import timescale, localize
>>> localize.furnsh_tls()

>>> et = spice.str2et(t0_utc.strftime('%FT%T'))
>>> print(et)
599963809.1840458

The ET is converted to TDT (=TT).

>>> tt = spice.unitim(et, 'ET', 'TDT')
>>> print(tt)
599963809.184

TAI is also obtained.

>>> tai = spice.unitim(et, 'ET', 'TAI')
>>> print(tai)
599963777.0

From the TAI, one can get UTC via ET as

>>> tai = 0
>>> et = spice.unitim(tai, 'TAI', 'ET')
>>> t_py = et2datetime(et)
>>> print(t_py)
2000-01-01 11:59:28
"""
import os as _os
import datetime as _datetime
import logging as _logging
import urllib.request as _ureq
import urllib.error as _uerr
import tempfile as _tempfile
import warnings as _warnings

from dateutil.parser import parse as _dateparse

import spiceypy as _spice

_logger = _logging.getLogger(__name__)


[docs]def download_lsk(url=None, localname=None, update=False): """ Try to download LSK file from the NAIF's server. The downloading file is https://naif.jpl.nasa.gov/pub/naif/generic_kernels/lsk/latest_leapseconds.tls The downloaded file name becomes "latest_leapseconds.tls" in the ``tempfile.gettempdir()` unless specified by ``localname`` keyword. The file name is returned. """ _warnings.warn('Deprecated. Use irfpy.spice.localize.furnsh_tls() function', DeprecationWarning) if url is None: url = "https://naif.jpl.nasa.gov/pub/naif/generic_kernels/lsk/latest_leapseconds.tls" if localname is None: localname = 'latest_leapseconds.tls' localname = _os.path.join(_tempfile.gettempdir(), localname) _logger.info('Localname={}'.format(localname)) if (not update) and _os.path.exists(localname): _logger.info('Cache file {} exist. Not retrieving.'.format(localname)) return localname try: _logger.info('Try the url {}'.format(url)) with _ureq.urlopen(url) as response, open(localname, 'wb') as out_file: data = response.read() out_file.write(data) except _uerr.HTTPError as err: _logger.error("Failed to download the latest leapsecond kernel from the NAIF server.") raise err return localname
[docs]def datetime2et(t): """ Python's datetime is converted to ET >>> import datetime >>> t = datetime.datetime(2013, 5, 10, 4, 30, 25, 123456) >>> print(t) 2013-05-10 04:30:25.123456 >>> from irfpy.spice import localize >>> localize.furnsh_tls() >>> et = datetime2et(t) >>> print(et) 421432292.3088006 """ s = t.strftime('%FT%T.%f') try: et = _spice.str2et(s) except Exception: _logger.error('Failed to calculate ET. Maybe leapsecond kernel is not loaded.') raise return et
[docs]def et2datetime(et): """ ET is converted to python's datetime >>> from irfpy.spice import timescale, localize >>> import spiceypy as spice >>> localize.furnsh_tls() >>> et = 421432292.3088006 >>> t = et2datetime(et) >>> print(t) 2013-05-10 04:30:25.123456 """ utcstr = _spice.et2utc(et, 'C', 6) tpy = _dateparse(utcstr) return tpy