The astropy.time package provides functionality for manipulating times and dates. Specific emphasis is placed on supporting time scales (e.g., UTC, TAI, UT1, TDB) and time representations (e.g., JD, MJD, ISO 8601) that are used in astronomy and required to calculate, for example, sidereal times and barycentric corrections. The astropy.time package is based on fast and memory efficientPyERFA wrappers around the ERFA time and calendar routines.
All time manipulations and arithmetic operations are done internally using two 64-bit floats to represent time. Floating point algorithms from [1] are used so that the Time object maintains sub-nanosecond precision over times spanning the age of the universe.
The usual way to use astropy.time is to create a Time object by supplying one or more input time values as well as the time format and time scale of those values. The input time(s) can either be a single scalar like"2010-01-01 00:00:00" or a list or a numpy array of values as shown below. In general, any output values have the same shape (scalar or array) as the input.
import numpy as np
from astropy.time import Time
times = ['1999-01-01T00:00:00.123456789', '2010-01-01T00:00:00']
t = Time(times, format='isot', scale='utc')
t
<Time object: scale='utc' format='isot' value=['1999-01-01T00:00:00.123' '2010-01-01T00:00:00.000']>
t[1]
The format argument specifies how to interpret the input values (e.g., ISO, JD, or Unix time). By default, the same format will be used to represent the time for output. One can change this format later as needed, but because this is just for representation, that does not affect the internal representation (which is always by two 64-bit values, the jd1 and jd2 attributes), nor any computations with the object.
The scale argument specifies the time scale for the values (e.g., UTC, TT, or UT1). The scale argument is optional and defaults to UTC except for Time from Epoch Formats. It is possible to change it (e.g., from UTC to TDB), which will cause the internal values to be adjusted accordingly.
We could have written the above as:
t = Time(times, format='isot')
When the format of the input can be unambiguously determined, theformat argument is not required, so we can then simplify even further:
Now we can get the representation of these times in the JD and MJD formats by requesting the corresponding Time attributes:
The full power of output representation is available via theto_value method which also allows controlling thesubformat. For instance, using numpy.longdouble as the output type for higher precision:
We can also convert to a different time scale, for instance from UTC to TT. This uses the same attribute mechanism as above but now returns a newTime object:
Note that both the ISO (ISOT) and JD representations of t2 are different than for t because they are expressed relative to the TT time scale. Of course, from the numbers or strings you would not be able to tell this was the case:
You can set the time values in place using the usual numpy array setting item syntax:
t2 = t.tt.copy() # Copy required if transformed Time will be modified
t2[1] = '2014-12-25'
print(t2)
['1999-01-01T00:01:04.307' '2014-12-25T00:00:00.000']
The Time object also has support for missing values, which is particularly useful for Table Operations such as joining and stacking:
t2[0] = np.ma.masked # Declare that first time is missing or invalid
print(t2)
[ ——— '2014-12-25T00:00:00.000']
Finally, some further examples of what is possible. For details, see the API documentation below.
dt = t[1] - t[0]
dt
Here, note the conversion of the timescale to TAI. Time differences can only have scales in which one day is always equal to 86400 seconds.
You can also use time-based Quantity for time arithmetic:
import astropy.units as u
Time("2020-01-01") + 5 * u.day
<Time object: scale='utc' format='iso' value=2020-01-06 00:00:00.000>
As of v5.1, Time objects can also be passed directly tonumpy.linspace to create even-sampled time arrays, including support for non-scalar start and/or stop points - given compatible shapes.
In astropy.time a “time” is a single instant of time which is independent of the way the time is represented (the “format”) and the time “scale” which specifies the offset and scaling relation of the unit of time. There is no distinction made between a “date” and a “time” since both concepts (as loosely defined in common usage) are just different representations of a moment in time.
The time format specifies how an instant of time is represented. The currently available formats are can be found in the Time.FORMATS dict and are listed in the table below. Each of these formats is implemented as a class that derives from the base TimeFormat class. This class structure can be adapted and extended by users for specialized time formats not supplied inastropy.time.
Note
The TimeFITS format implements most of the FITS standard [2], including support for the LOCAL timescale. Note, though, that FITS supports some deprecated names for timescales; these are translated to the formal names upon initialization. Furthermore, any specific realization information, such as UT(NIST) is stored only as long as the time scale is not changed.
The default representation can be changed by setting the format attribute:
t = Time('2000-01-02')
t.format = 'jd'
t
Be aware that when changing format, the current output subformat (see section below) may not exist in the new format. In this case, the subformat will not be preserved:
Many of the available time format classes support the concept of a subformat. This allows for variations on the basic theme of a format in both the input parsing/validation and the output.
The table below illustrates available subformats for the string formats
iso, fits, and yday formats:
Numerical formats such as mjd, jyear, or cxcsec all support the subformats: 'float', 'long', 'decimal', 'str', and 'bytes'. Here, 'long' uses numpy.longdouble for somewhat enhanced precision (with the enhancement depending on platform), and 'decimal' instances ofdecimal.Decimal for full precision. For the 'str' and 'bytes'subformats, the number of digits is also chosen such that time values are represented accurately.
When used on input, these formats allow creating a time using a single input value that accurately captures the value to the full available precision inTime. Conversely, the single value on output using Timeto_value or TimeDeltato_valuecan have higher precision than the standard 64-bit float:
tm = Time('51544.000000000000001', format='mjd') # String input
tm.mjd # float64 output loses last digit but Decimal gets it
np.float64(51544.0)
tm.to_value('mjd', subfmt='decimal')
Decimal('51544.00000000000000099920072216264')
tm.to_value('mjd', subfmt='str')
'51544.000000000000001'
The complete list of subformat options for the Time formats that have them is:
The complete list of subformat options for the TimeDelta formats that have them is:
The formats cxcsec, gps, unix, and unix_tai are special in that they provide a floating point representation of the elapsed time in seconds since a particular reference date. These formats have a intrinsic time scale which is used to compute the elapsed seconds since the reference date.
Unlike the other formats which default to UTC, if no scale is provided when initializing a Time object then the above intrinsic scale is used. This is done for computational efficiency.
The local time scale is meant for free-running clocks or simulation times (i.e., to represent a time without a properly defined scale). This means it cannot be converted to any other time scale, and arithmetic is possible only with Time instances with scale local and with TimeDelta instances with scale local or None.
The system of transformation between supported time scales (i.e., all butlocal) is shown in the figure below. Further details are provided in theConvert time scale section.
A Time object can hold either a single time value or an array of time values. The distinction is made entirely by the form of the input time(s). If a Timeobject holds a single value then any format outputs will be a single scalar value, and likewise for arrays.
Like other arrays and lists, Time objects holding arrays are subscriptable, returning scalar or array objects as appropriate:
from astropy.time import Time
t = Time(100.0, format='mjd')
t.jd
np.float64(2400100.5)
t = Time([100.0, 200.0, 300.], format='mjd')
t.jd
array([2400100.5, 2400200.5, 2400300.5])
t[:2]
<Time object: scale='utc' format='mjd' value=[100. 200.]>
t[2]
NumPy Method Analogs and Applicable NumPy Functions#
For Time instances holding arrays, many of the same methods and attributes that work on ndarray instances can be used. For example, you can reshape Time instances and take specific parts usingreshape(), ravel(),flatten(), T,transpose(), swapaxes(),diagonal(), squeeze(), ortake(). Corresponding functions, as well as others that affect the shape, such as atleast_1d and rollaxis, work as expected. (The relevant functions have to be explicitly enabled inastropy source code; let us know if a numpy function is not supported that you think should work.)
Note that similarly to the ndarray methods, all butflatten() try to use new views of the data, with the data copied only if that is impossible (as discussed, for example, in the documentation for numpyreshape()).
The Time class initializer will not accept ambiguous inputs, but it will make automatic inferences in cases where the inputs are unambiguous. This can apply when the times are supplied as objects, inputs for ymdhms, or strings. In the latter case it is not required to specify the format because the available string formats have no overlap. However, if the format is known in advance the string parsing will be faster if the format is provided.
The Time object maintains an internal representation of time as a pair of double precision numbers expressing Julian days. The sum of the two numbers is the Julian Date for that time relative to the given time scale. Users requiring no better than microsecond precision over human time scales (~100 years) can safely ignore the internal representation details and skip this section.
This representation is driven by the underlying ERFA C-library implementation. The ERFA routines take care throughout to maintain overall precision of the double pair. Users are free to choose the way in which total JD is provided, though internally one part contains integer days and the other the fraction of the day, as this ensures optimal accuracy for all conversions. The internal JD pair is available via the jd1and jd2 attributes:
If a tuple, three Quantity items with length units for geocentric coordinates, or a longitude, latitude, and optional height for geodetic coordinates. Can be a single location, or one for each input time.
The val argument specifies the input time or times and can be a single string or number, or it can be a Python list or numpy array of strings or numbers. To initialize a Time object based on a specified time, it must be present.
In most situations, you also need to specify the time scale via thescale argument. The Time class will never guess the time scale, so a concise example would be:
It is possible to create a new Time object from one or more existing time objects. In this case, the format and scale will be inferred from the first object unless explicitly specified.
The val2 argument is available for those situations where high precision is required. Recall that the internal representation of time within astropy.timeis two double-precision numbers that when summed give the Julian date. If provided, the val2 argument is used in combination with val to set the second of the internal time values. The exact interpretation of val2 is determined by the input format class. All string-valued formats ignore val2and all numeric inputs effectively add the two values in a way that maintains the highest precision. For example:
The scale argument sets the time scale and is required except for time formats such as plot_date (TimePlotDate) and unix(TimeUnix). These formats represent the duration in SI seconds since a fixed instant in time is independent of time scale. See the Time from Epoch Formats for more details.
The precision setting affects string formats when outputting a value that includes seconds. It must be an integer between 0 and 9. There is no effect when inputting time values from strings. The default precision is 3. Note that the limit of 9 digits is driven by the way that ERFA handles fractional seconds. In practice this should should not be an issue.
The in_subfmt argument provides a mechanism to select one or moresubformat values from the available subformats for input. Multiple allowed subformats can be selected using Unix-style wildcard characters, in particular * and ?, as documented in the Python fnmatch module.
The default value for in_subfmt is * which matches any available subformat. This allows for convenient input of values with unknown or heterogeneous subformat:
You can explicitly specify in_subfmt in order to strictly require a certain subformat:
t = Time('2000:002:03:04', in_subfmt='date_hm')
t = Time('2000:002', in_subfmt='date_hm')
Traceback (most recent call last):
...
ValueError: Input values did not match any of the formats where the
format keyword is optional ['astropy_time', 'datetime',
'byear_str', 'iso', 'isot', 'jyear_str', 'yday']
The out_subfmt argument is similar to in_subfmt except that it applies to output formatting. In the case of multiple matching subformats, the first matching subformat is used.
This optional parameter specifies the observer location, using anEarthLocation object or a tuple containing any form that can initialize one: either a tuple with geocentric coordinates (X, Y, Z), or a tuple with geodetic coordinates (longitude, latitude, height; with height defaulting to zero). They are used for time scales that are sensitive to observer location (currently, only TDB, which relies on the PyERFA routine erfa.dtdb to determine the time offset between TDB and TT), as well as for sidereal time if no explicit longitude is given.
Time formats that are based on a date string representation of time, includingTimeISO, TimeISOT, andTimeYearDayTime, make use of a fast C-based date parser that improves speed by a factor of 20 or more for large arrays of times.
The C parser is stricter than the Python-based parser (which relies onstrptime). In particular fields like the month or day of year must always have a fixed number of ASCII digits. As an example the Python parser will accept 2000-1-2T3:04:5.23 while the C parser requires2000-01-02T03:04:05.23
Use of the C parser is enabled by default except when the input subformatin_subfmt argument is different from the default value of '*'. If the fast C parser fails to parse the date values then the Time initializer will automatically fall through to the Python parser.
In rare cases where you need to explicitly control which parser gets used there is a configuration item time.conf.use_fast_parser that can be set. The default is 'True', which means to try the fast parser and fall through to Python parser if needed. Note that the configuration value is a string, not a bool object.
For example to disable the C parser use:
from astropy.time import conf
date = '2000-1-2T3:04:5.23'
t = Time(date, format='isot') # Succeeds by default
with conf.set_temp('use_fast_parser', 'False'):
... t = Time(date, format='isot')
... print(t)
2000-01-02T03:04:05.230
To force the user of the C parser (for example in testing) use:
with conf.set_temp('use_fast_parser', 'force'):
... try:
... t = Time(date, format='isot')
... except ValueError as err:
... print(err)
Input values did not match the format class isot:
ValueError: fast C time string parser failed: non-digit found where digit (0-9) required
For an existing Time object which is array-valued, you can use the usual numpy array item syntax to get either a single item or a subset of items. The returned value is a Time object with all the same attributes.
The new value (on the right hand side) when setting can be one of three possibilities:
Scalar string value or array of string values where each value is in a valid time format that can be automatically parsed and used to create a Time object.
Value or array of values where each value has the same format as the Time object being set. For instance, a float or numpy array of floats for an object with format='unix'.
Time object with identical location (but scale andformat need not be the same). The right side value will be transformed so the time scale matches.
Whenever any item is set, then the internal cache (see Caching) is cleared along with the delta_tdb_tt and/or delta_ut1_utc transformation offsets, if they have been set.
If it is required that the Time object be immutable, then set thewriteable attribute to False. In this case, attempting to set a value will raise a ValueError: Time object is read-only. See the section onCaching for an example.
The Time and TimeDelta objects support functionality for marking values as missing or invalid. This is also known as masking, and is especially useful forTable Operations such as joining and stacking.
If you want to get unmasked data, you can get those either by removing the mask using the unmasked attribute, or by filling any masked data with a chosen value:
A subtle difference between the two approaches is that when you unset the mask by setting with numpy.ma.nomask, a mask is still present internally, and hence any output will have a mask as well. In contrast, using unmasked orfilled() removes all masking, and hence any output is not masked. The masked property can be used to check whether or not a mask is in use internally:
When setting the mask, actual time data are kept. However, when initializing with a masked array, any masked time input data are overwritten internally, with a time equivalent to 2000-01-01 12:00:00 (in the same scale and format as the other values). This is to ensure no errors or warnings are raised by invalid data hidden by the mask. Hence, for initialization with masked data, there is no way to recover the original masked values:
Once one or more values in the object are masked, any operations will propagate those values as masked, and access to format attributes such as unix or value will return a Masked object:
You can view the mask, but note that it is read-only. Setting and clearing the mask is always done by setting the item tomasked and nomask, respectively.
Time internally uses astropy’s Masked class to represent the mask. It is possible to initialize with data using numpy’s MaskedArray class, but by default all output will use Masked. For backward compatibility, it is possible to set masked_array_type to “numpy” to ensure that output uses MaskedArray where possible (for all but Quantity).
For advanced users who have written a custom time format via aTimeFormat subclass, it may be necessary to modify your class_if you wish to support masked values_, and especially if you earlier supported having missing values by setting the jd2 attribute tonumpy.nan. For applications that do not need masked or missing values, no changes are required.
Prior to astropy 6.0, missing values in a TimeFormat subclass object were marked by setting the corresponding entries of the jd2attribute to be numpy.nan (but this was never done directly by the user). Since astropy 6.0, instead Masked arrays are used, and these are written to propagate properly through (almost) all numpy and ERFA functions.
In general, very few modifications should be needed to support Maskedarrays. Generally, on input, no changes are needed since the format will be given unmasked values (with any masked input values replaced with the default value to ensure that only valid values are passed in). Some care may need to be taken, though, that the mask is propagated properly in calculating output values from jd1 to jd2 in the value property.
Instants of time can be represented in different ways, for instance as an ISO-format date string ('1999-07-23 04:31:00') or seconds since 1998.0 (49091460.0) or Modified Julian Date (51382.187451574).
The representation of a Time object in a particular format is available by getting the object attribute corresponding to the format name. The list of available format names is in the time format section.
t = Time('2010-01-01 00:00:00', format='iso', scale='utc')
t.jd # JD representation of time in current scale (UTC)
np.float64(2455197.5)
t.iso # ISO representation of time in current scale (UTC)
'2010-01-01 00:00:00.000'
t.unix # seconds since 1970.0 (UTC)
np.float64(1262304000.0)
t.datetime # Representation as datetime.datetime object
datetime.datetime(2010, 1, 1, 0, 0)
import matplotlib.pyplot as plt
jyear = np.linspace(2000, 2001, 20)
t = Time(jyear, format='jyear')
plt.plot_date(t.plot_date, jyear)
plt.gcf().autofmt_xdate() # orient date labels at a slant
plt.draw()
A new Time object for the same time value(s) but referenced to a new time scale can be created getting the object attribute corresponding to the time scale name. The list of available time scale names is in the time scalesection and in the figure below illustrating the network of time scale transformations.
In this process the format and other object attributes like lon,lat, and precision are also propagated to the new object.
As noted in the Time Object Basics section, a Time object can only be changed by explicitly setting some of its elements. The process of changing the time scale therefore begins by making a copy of the original object and then converting the internal time values in the copy to the new time scale. The newTime object is returned by the attribute access.
The computations for transforming to different time scales or formats can be time-consuming for large arrays. In order to avoid repeated computations, eachTime or TimeDelta instance caches such transformations internally:
t = Time(np.arange(1e6), format='unix', scale='utc')
time x = t.tt
CPU times: user 263 ms, sys: 4.02 ms, total: 267 ms
Wall time: 267 ms
time x = t.tt
CPU times: user 28 µs, sys: 9 µs, total: 37 µs
Wall time: 32.9 µs
Actions such as changing the output precision or subformat will clear the cache. In order to explicitly clear the internal cache do:
del t.cache
time x = t.tt
CPU times: user 263 ms, sys: 4.02 ms, total: 267 ms
Wall time: 267 ms
In order to ensure consistency between the transformed (and cached) version and the original, the transformed object is set to be not writeable. For example:
x = t.tt
x[1] = '2000:001'
Traceback (most recent call last):
...
ValueError: Time object is read-only. Make a copy() or set "writeable" attribute to True.
If you require modifying the object then make a copy first, for example, x = t.tt.copy().
Time scale transformations that cross one of the orange circles in the image above require an additional offset time value that is model or observation dependent. See SOFATime Scale and Calendar Tools for further details.
The two attributes delta_ut1_utc anddelta_tdb_tt provide a way to set these offset times explicitly. These represent the time scale offsets UT1 - UTC and TDB - TT, respectively. As an example:
t = Time('2010-01-01 00:00:00', format='iso', scale='utc')
t.delta_ut1_utc = 0.334 # Explicitly set one part of the transformation
t.ut1.iso # ISO representation of time in UT1 scale
'2010-01-01 00:00:00.334'
For the UT1 to UTC offset, you have to interpolate the observed values provided by the International Earth Rotation and Reference Systems (IERS) Service. astropy will automatically download and use values from the IERS which cover times spanning from 1973-Jan-01 through one year into the future. In addition, the astropy package is bundled with a data table of values provided in Bulletin B, which cover the period from 1962 to shortly before an astropy release.
When the delta_ut1_utc attribute is not set explicitly, IERS values will be used (initiating a download of a few Mb file the first time). For details about how IERS values are used in astropytime and coordinates, and to understand how to control automatic downloads, seeIERS data access (astropy.utils.iers). The example below illustrates converting to the UT1scale along with the auto-download feature:
The IERS_Auto class contains machinery to ensure that the IERS table is kept up to date by auto-downloading the latest version as needed. This means that the IERS table is assured of having the state-of-the-art definitive and predictive values for Earth rotation. As a user it is your responsibility to understand the accuracy of IERS predictions if your science depends on that. If you request UT1-UTC for times beyond the range of IERS table data then the nearest available values will be provided.
In the case of the TDB to TT offset, most users need only provide the lonand lat values when creating the Time object. If thedelta_tdb_tt attribute is not explicitly set, then the PyERFA routine erfa.dtdb will be used to compute the TDB to TT offset. Note that if lon and lat are not explicitly initialized, values of 0.0 degrees for both will be used.
The following code replicates an example in the SOFATime Scale and Calendar Tools document. It does the transform from UTC to all supported time scales (TAI, TCB, TCG, TDB, TT, UT1, UTC). This requires an observer location (here, latitude and longitude).
A user can generate a unique hash key for scalar (0-dimensional) Time orTimeDelta objects. The key is based on a tuple of jd1,jd2, scale, and location (if present, None otherwise).
Note that two Time objects with a different scale can compare equally but still have different hash keys. This a practical consideration driven in by performance, but in most cases represents a desirable behavior.
If your times array contains a lot of elements, the value argument will display all the elements of the Time object t when it is called or printed. To control the number of elements to be displayed, set thethreshold argument with np.printoptions as follows:
Apparent or mean sidereal time can be calculated usingsidereal_time(). The method returns a Longitudewith units of hour angle, which by default is for the longitude corresponding to the location with which the Time object is initialized. Like the scale transformations, ERFA C-library routines are used under the hood, which support calculations following different IAU resolutions.
Similarly, one can calculate the Earth rotation angle withearth_rotation_angle(). Unlike sidereal time, which is referred to the equinox and is a complicated function of both UT1 and Terrestrial Time, the Earth rotation angle is referred to the Celestial Intermediate Origin (CIO) and is a linear function of UT1 alone.
For the recent IAU precession models, as well as for the Earth rotation angle, the result includes the TIO locator (s’), which positions the Terrestrial Intermediate Origin on the equator of the Celestial Intermediate Pole (CIP) and is rigorously corrected for polar motion.
The TimeDelta class is derived from the Time class and shares many of its properties. One difference is that the time scale has to be one for which one day is exactly 86400 seconds. Hence, the scale cannot be UTC.
Quantity objects with time units can also be used in place of TimeDelta.
import astropy.units as u
t1 + 1 * u.hour
<Time object: scale='utc' format='iso' value=2010-01-01 01:00:00.000>
A human-readable multi-scale format for string representation of a time delta is available via the quantity_str format. See theTimeDeltaQuantityString class docstring for more details:
The now deprecated default assumes days for numeric inputs:
t1 + 5.0
<Time object: scale='utc' format='iso' value=2010-01-06 00:00:00.000>
TimeDeltaMissingUnitWarning: Numerical value without unit or explicit format passed to TimeDelta, assuming days
The TimeDelta has a to_value method which supports controlling the type of the output representation by providing either a format name and optional subformat or a valid astropy unit:
We have shown in the above that the difference between two UTC times is aTimeDelta with a scale of TAI. This is because a UTC time difference cannot be uniquely defined unless the user knows the two times that were differenced (because of leap seconds, a day does not always have 86400 seconds). For all other time scales, the TimeDelta inherits the scale of the first Timeobject.
When TimeDelta objects are added or subtracted from Time objects, scales are converted appropriately, with the final scale being that of the Timeobject:
TimeDelta objects can be converted only to objects with compatible scales (i.e., scales for which it is not necessary to know the times that were differenced):
dt.tt
dt.tdb
Traceback (most recent call last):
...
ScaleValueError: Cannot convert TimeDelta with scale 'tcg' to scale 'tdb'
TimeDelta objects can also have an undefined scale, in which case it is assumed that their scale matches that of the other Time or TimeDeltaobject (or is TAI in case of a UTC time):
Since internally Time uses floating point numbers, round-off errors can cause two times to be not strictly equal even if mathematically they should be. For times in UTC in particular, this can lead to surprising behavior, because when you add aTimeDelta, which cannot have a scale of UTC, the UTC time is first converted to TAI, then the addition is done, and finally the time is converted back to UTC. Hence, rounding errors can be incurred, which means that even expected equalities may not hold:
t = Time(2450000., 1e-6, format='jd')
t + TimeDelta(0, format='jd') == t
False
Barycentric and Heliocentric Light Travel Time Corrections#
The arrival times of photons at an observatory are not particularly useful for accurate timing work, such as eclipse/transit timing of binaries or exoplanets. This is because the changing location of the observatory causes photons to arrive early or late. The solution is to calculate the time the photon would have arrived at a standard location; either the Solar System barycenter or the heliocenter.
Suppose you observed the dwarf nova IP Peg from Greenwich and have a list of times in MJD form, in the UTC timescale. You then create appropriate Time andSkyCoord objects and calculate light travel times to the barycenter as follows:
from astropy import time, coordinates as coord, units as u
ip_peg = coord.SkyCoord("23:23:08.55", "+18:24:59.3",
... unit=(u.hourangle, u.deg), frame='icrs')
greenwich = coord.EarthLocation.of_site('greenwich')
times = time.Time([56325.95833333, 56325.978254], format='mjd',
... scale='utc', location=greenwich)
ltt_bary = times.light_travel_time(ip_peg)
ltt_bary
<TimeDelta object: scale='tdb' format='jd' value=[-0.0037715 -0.00377286]>
If you desire the light travel time to the heliocenter instead, then use:
The method returns an TimeDelta object, which can be added to your times to give the arrival time of the photons at the barycenter or heliocenter. Here, you should be careful with the timescales used; for more detailed information about timescales, see Time Scale.
The heliocenter is not a fixed point, and therefore the gravity continually changes at the heliocenter. Thus, the use of a relativistic timescale like TDB is not particularly appropriate, and, historically, times corrected to the heliocenter are given in the UTC timescale:
times_heliocentre = times.utc + ltt_helio
Corrections to the barycenter are more precise than the heliocenter, because the barycenter is a fixed point where gravity is constant. For maximum accuracy you want to have your barycentric corrected times in a timescale that has always ticked at a uniform rate, and ideally one whose tick rate is related to the rate that a clock would tick at the barycenter. For this reason, barycentric corrected times normally use the TDB timescale:
time_barycentre = times.tdb + ltt_bary
By default, the light travel time is calculated using the position and velocity of Earth and the Sun from ERFAroutines, but you can also get more precise calculations using the JPL ephemerides (which are derived from dynamical models). An example using the JPL ephemerides is:
The difference between the built-in ephemerides and the JPL ephemerides is normally of the order of 1/100th of a millisecond, so the built-in ephemerides should be suitable for most purposes. For more details about what ephemerides are available, including the requirements for using JPL ephemerides, seeSolar System Ephemerides.
Where possible, Quantity objects with units of time are treated as TimeDeltaobjects with undefined scale (though necessarily with lower precision). They can also be used as input in constructing Time and TimeDelta objects, andTimeDelta objects can be converted to Quantity objects of arbitrary units of time.
import astropy.units as u
Time(10.*u.yr, format='gps') # time-valued quantities can be used for
... # for formats requiring a time offset
Time(10.*u.yr, 1.*u.s, format='gps')
Time(2000.*u.yr, format='jyear')
Time(2000.*u.yr, format='byear')
... # but not for Besselian year, which implies
... # a different time scale
...
Traceback (most recent call last):
...
ValueError: Input values did not match the format class byear:
ValueError: cannot use Quantities for 'byear' format, as the unit of year is defined as 365.25 days, while the length of year is variable in this format. Use float instead.
TimeDelta(10.*u.yr) # With a quantity, no format is required
dt = TimeDelta([10., 20., 30.], format='jd')
dt.to(u.hr) # can convert TimeDelta to a quantity
<Quantity [240., 480., 720.] h>
dt > 400. * u.hr # and compare to quantities with units of time
array([False, True, True]...)
dt + 1.*u.hr # can also add/subtract such quantities
<TimeDelta object: scale='None' format='jd' value=[10.04166667 20.04166667 30.04166667]>
Time(50000., format='mjd', scale='utc') + 1.*u.hr
dt * 10.*u.km/u.s # for multiplication and division with a
... # Quantity, TimeDelta is converted
<Quantity [100., 200., 300.] d km / s>
dt * 10.*u.Unit(1) # unless the Quantity is dimensionless
<TimeDelta object: scale='None' format='jd' value=[100. 200. 300.]>
Some applications may need a custom Time format, and this capability is available by making a new subclass of the TimeFormat class. When such a subclass is defined in your code, the format class and corresponding name is automatically registered in the set of available time formats.
The key elements of a new format class are illustrated by examining the code for the jd format (which is one of the most minimal):
class TimeJD(TimeFormat):
"""
Julian Date time format.
"""
name = 'jd' # Unique format name
def set_jds(self, val1, val2):
"""
Set the internal jd1 and jd2 values from the input val1, val2.
The input values are expected to conform to this format, as
validated by self._check_val_type(val1, val2) during __init__.
"""
self._check_scale(self._scale) # Validate scale.
self.jd1, self.jd2 = day_frac(val1, val2)
@property
def value(self):
"""
Return format ``value`` property from internal jd1, jd2
"""
return self.jd1 + self.jd2
As mentioned above, the _check_val_type(self, val1, val2)method may need to be overridden to validate the inputs as conforming to the format specification. By default this checks for valid float, float array, orQuantity inputs. In contrast, the iso format class ensures the inputs meet the ISO format specification for strings.
One special case that is relatively common and more convenient to implement is a format that makes a small change to the date format. For instance, you could insert T in the yday format with the following TimeYearDayTimeCustomclass. Notice how the subfmts definition is modified slightly from the standard TimeISO class from which it inherits:
from astropy.time import TimeISO
class TimeYearDayTimeCustom(TimeISO):
... """
... Year, day-of-year and time as "-T::<SS.sss...>".
... The day-of-year (DOY) goes from 001 to 365 (366 in leap years).
... For example, 2000-001T00:00:00.000 is midnight on January 1, 2000.
... The allowed subformats are:
... - 'date_hms': date + hours, mins, secs (and optional fractional secs)
... - 'date_hm': date + hours, mins
... - 'date': date
... """
... name = 'yday_custom' # Unique format name
... subfmts = (('date_hms',
... '%Y-%jT%H:%M:%S',
... '{year:d}-{yday:03d}T{hour:02d}:{min:02d}:{sec:02d}'),
... ('date_hm',
... '%Y-%jT%H:%M',
... '{year:d}-{yday:03d}T{hour:02d}:{min:02d}'),
... ('date',
... '%Y-%j',
... '{year:d}-{yday:03d}'))
Another special case that is relatively common is a format that represents the time since a particular epoch. The classic example is Unix time which is the number of seconds since 1970-01-01 00:00:00 UTC, not counting leap seconds. What if we wanted that value but do want to count leap seconds. This would be done by using the TAI scale instead of the UTC scale. In this case we inherit from the TimeFromEpoch class and define a few class attributes:
from astropy.time.formats import erfa, TimeFromEpoch
class TimeUnixLeap(TimeFromEpoch):
... """
... Seconds from 1970-01-01 00:00:00 TAI. Similar to Unix time
... but this includes leap seconds.
... """
... name = 'unix_leap'
... unit = 1.0 / erfa.DAYSEC # in days (1 day == 86400 seconds)
... epoch_val = '1970-01-01 00:00:00'
... epoch_val2 = None
... epoch_scale = 'tai' # Scale for epoch_val class attribute
... epoch_format = 'iso' # Format for epoch_val class attribute
t = Time('2000-01-01')
t.unix_leap
np.float64(946684832.0)
t.unix_leap - t.unix
np.float64(32.0)
Going beyond this will probably require looking at the astropy code for more guidance, but if you get stuck, the astropy developers are more than happy to help. If you write a format class that is widely useful we might want to include it in the core!
When a Time object is constructed from a timezone-awaredatetime, no timezone information is saved in theTime object. However, Time objects can be converted to timezone-aware datetime objects.
To convert a Time object to a timezone-aware datetime object:
from datetime import datetime
from astropy.time import Time, TimezoneInfo
import astropy.units as u
utc_plus_one_hour = TimezoneInfo(utc_offset=1*u.hour)
dt_aware = datetime(2000, 1, 1, 0, 0, 0, tzinfo=utc_plus_one_hour)
t = Time(dt_aware) # Loses timezone info, converts to UTC
print(t) # will return UTC
1999-12-31 23:00:00
print(t.to_datetime(timezone=utc_plus_one_hour)) # to timezone-aware datetime
2000-01-01 00:00:00+01:00
Timezone database packages, like pytzfor example, may be more convenient to use to create tzinfoobjects used to specify timezones rather than the TimezoneInfoobject.
Using the dateutil package, you can parse times in a wide variety of supported formats to generate adatetime.datetime object which can then be used to initialize a Time object:
The Time object supports output string representation using the format specification language defined in the Python standard library for time.strftime. This can be done using the strftimemethod.
To get output string representation using the strftimemethod:
from astropy.time import Time
t = Time('2018-01-01T10:12:58')
t.strftime('%H:%M:%S %d %b %Y')
'10:12:58 01 Jan 2018'
Conversely, to create a Time object from a custom date string that can be parsed with Python standard library time.strptime (using the same format language linked above), use the strptime class method:
from astropy.time import Time
t = Time.strptime('23:59:60 30 June 2015', '%H:%M:%S %d %B %Y')
t
This package makes use of the PyERFA wrappers of the ERFA ANSI C library. The copyright of the ERFAsoftware belongs to the NumFOCUS Foundation. The library is made available under the terms of the “BSD-three clauses” license.
The ERFA library is derived, with permission, from the International Astronomical Union’s “Standards of Fundamental Astronomy” (SOFA) library, available from http://www.iausofa.org.