TimeDelta

class astropy.time.TimeDelta(val, val2=None, format=None, scale=None, copy=False)[source] [edit on github]

Bases: astropy.time.Time

Represent the time difference between two times.

A TimeDelta object is initialized with one or more times in the val argument. The input times in val must conform to the specified format. The optional val2 time input should be supplied only for numeric input formats (e.g. JD) where very high precision (better than 64-bit precision) is required.

The allowed values for format can be listed with:

>>> list(TimeDelta.FORMATS)
['sec', 'jd', 'datetime']

Note that for time differences, the scale can be among three groups: geocentric (‘tai’, ‘tt’, ‘tcg’), barycentric (‘tcb’, ‘tdb’), and rotational (‘ut1’). Within each of these, the scales for time differences are the same. Conversion between geocentric and barycentric is possible, as there is only a scale factor change, but one cannot convert to or from ‘ut1’, as this requires knowledge of the actual times, not just their difference. For a similar reason, ‘utc’ is not a valid scale for a time difference: a UTC day is not always 86400 seconds.

Parameters:
val : sequence, ndarray, number, Quantity or TimeDelta object

Value(s) to initialize the time difference(s). Any quantities will be converted appropriately (with care taken to avoid rounding errors for regular time units).

val2 : sequence, ndarray, number, or Quantity; optional

Additional values, as needed to preserve precision.

format : str, optional

Format of input value(s)

scale : str, optional

Time scale of input value(s), must be one of the following values: (‘tdb’, ‘tt’, ‘ut1’, ‘tcg’, ‘tcb’, ‘tai’). If not given (or None), the scale is arbitrary; when added or subtracted from a Time instance, it will be used without conversion.

copy : bool, optional

Make a copy of the input values

Attributes Summary

FORMATS Dict of time delta formats.
SCALES List of time delta scales.
T Return an instance with the data transposed.
cache Return the cache associated with this instance.
delta_tdb_tt
delta_ut1_utc Get ERFA DUT arg = UT1 - UTC.
format Get or set time format.
in_subfmt Unix wildcard pattern to select subformats for parsing string input times.
info
isscalar
jd1 First of the two doubles that internally store time value(s) in JD.
jd2 Second of the two doubles that internally store time value(s) in JD.
mask
masked
ndim The number of dimensions of the instance and underlying arrays.
out_subfmt Unix wildcard pattern to select subformats for outputting times.
precision Decimal precision when outputting seconds as floating point (int value between 0 and 9 inclusive).
scale Time scale
shape The shape of the time instances.
size The size of the object, as calculated from its shape.
value Time value(s) in current format
writeable

Methods Summary

argmax([axis, out]) Return indices of the maximum values along the given axis.
argmin([axis, out]) Return indices of the minimum values along the given axis.
argsort([axis]) Returns the indices that would sort the time array.
copy([format]) Return a fully independent copy the Time object, optionally changing the format.
diagonal(*args, **kwargs) Return an instance with the specified diagonals.
flatten(*args, **kwargs) Return a copy with the array collapsed into one dimension.
get_delta_ut1_utc([iers_table, return_status]) Find UT1 - UTC differences by interpolating in IERS Table.
light_travel_time(skycoord[, kind, …]) Light travel time correction to the barycentre or heliocentre.
max([axis, out, keepdims]) Maximum along a given axis.
min([axis, out, keepdims]) Minimum along a given axis.
now() Creates a new object corresponding to the instant in time this method is called.
ptp([axis, out, keepdims]) Peak to peak (maximum - minimum) along a given axis.
ravel(*args, **kwargs) Return an instance with the array collapsed into one dimension.
replicate(*args, **kwargs) Return a replica of the Time object, optionally changing the format.
reshape(*args, **kwargs) Returns an instance containing the same data with a new shape.
sidereal_time(kind[, longitude, model]) Calculate sidereal time.
sort([axis]) Return a copy sorted along the specified axis.
squeeze(*args, **kwargs) Return an instance with single-dimensional shape entries removed
strftime(format_spec) Convert Time to a string or a numpy.array of strings according to a format specification.
strptime(time_string, format_string, **kwargs) Parse a string to a Time according to a format specification.
swapaxes(*args, **kwargs) Return an instance with the given axes interchanged.
take(indices[, axis, mode]) Return a new instance formed from the elements at the given indices.
to(*args, **kwargs)
to_datetime() Convert to datetime.timedelta object.
transpose(*args, **kwargs) Return an instance with the data transposed.

Attributes Documentation

FORMATS = {'datetime': <class 'astropy.time.formats.TimeDeltaDatetime'>, 'jd': <class 'astropy.time.formats.TimeDeltaJD'>, 'sec': <class 'astropy.time.formats.TimeDeltaSec'>}

Dict of time delta formats.

SCALES = ('tai', 'tt', 'tcg', 'tcb', 'tdb', 'ut1', 'local')

List of time delta scales.

T

Return an instance with the data transposed.

Parameters are as for T. All internal data are views of the data of the original.

cache

Return the cache associated with this instance.

delta_tdb_tt
delta_ut1_utc

Get ERFA DUT arg = UT1 - UTC. This getter takes optional jd1 and jd2 args because it gets called that way when converting time scales. If delta_ut1_utc is not yet set, this will interpolate them from the the IERS table.

format

Get or set time format.

The format defines the way times are represented when accessed via the .value attribute. By default it is the same as the format used for initializing the Time instance, but it can be set to any other value that could be used for initialization. These can be listed with:

>>> list(Time.FORMATS)
['jd', 'mjd', 'decimalyear', 'unix', 'cxcsec', 'gps', 'plot_date',
 'datetime', 'iso', 'isot', 'yday', 'fits', 'byear', 'jyear', 'byear_str',
 'jyear_str']
in_subfmt

Unix wildcard pattern to select subformats for parsing string input times.

info
isscalar
jd1

First of the two doubles that internally store time value(s) in JD.

jd2

Second of the two doubles that internally store time value(s) in JD.

mask
masked
ndim

The number of dimensions of the instance and underlying arrays.

out_subfmt

Unix wildcard pattern to select subformats for outputting times.

precision

Decimal precision when outputting seconds as floating point (int value between 0 and 9 inclusive).

scale

Time scale

shape

The shape of the time instances.

Like shape, can be set to a new shape by assigning a tuple. Note that if different instances share some but not all underlying data, setting the shape of one instance can make the other instance unusable. Hence, it is strongly recommended to get new, reshaped instances with the reshape method.

Raises:
AttributeError

If the shape of the jd1, jd2, location, delta_ut1_utc, or delta_tdb_tt attributes cannot be changed without the arrays being copied. For these cases, use the Time.reshape method (which copies any arrays that cannot be reshaped in-place).

size

The size of the object, as calculated from its shape.

value

Time value(s) in current format

writeable

Methods Documentation

argmax(axis=None, out=None) [edit on github]

Return indices of the maximum values along the given axis.

This is similar to argmax(), but adapted to ensure that the full precision given by the two doubles jd1 and jd2 is used. See argmax() for detailed documentation.

argmin(axis=None, out=None) [edit on github]

Return indices of the minimum values along the given axis.

This is similar to argmin(), but adapted to ensure that the full precision given by the two doubles jd1 and jd2 is used. See argmin() for detailed documentation.

argsort(axis=-1) [edit on github]

Returns the indices that would sort the time array.

This is similar to argsort(), but adapted to ensure that the full precision given by the two doubles jd1 and jd2 is used, and that corresponding attributes are copied. Internally, it uses lexsort(), and hence no sort method can be chosen.

copy(format=None) [edit on github]

Return a fully independent copy the Time object, optionally changing the format.

If format is supplied then the time format of the returned Time object will be set accordingly, otherwise it will be unchanged from the original.

In this method a full copy of the internal time arrays will be made. The internal time arrays are normally not changeable by the user so in most cases the replicate() method should be used.

Parameters:
format : str, optional

Time format of the copy.

Returns:
tm : Time object

Copy of this object

diagonal(*args, **kwargs) [edit on github]

Return an instance with the specified diagonals.

Parameters are as for diagonal(). All internal data are views of the data of the original.

flatten(*args, **kwargs) [edit on github]

Return a copy with the array collapsed into one dimension.

Parameters are as for flatten().

get_delta_ut1_utc(iers_table=None, return_status=False) [edit on github]

Find UT1 - UTC differences by interpolating in IERS Table.

Parameters:
iers_table : astropy.utils.iers.IERS table, optional

Table containing UT1-UTC differences from IERS Bulletins A and/or B. If None, use default version (see astropy.utils.iers)

return_status : bool

Whether to return status values. If False (default), iers raises IndexError if any time is out of the range covered by the IERS table.

Returns:
ut1_utc : float or float array

UT1-UTC, interpolated in IERS Table

status : int or int array

Status values (if return_status=`True`):: astropy.utils.iers.FROM_IERS_B astropy.utils.iers.FROM_IERS_A astropy.utils.iers.FROM_IERS_A_PREDICTION astropy.utils.iers.TIME_BEFORE_IERS_RANGE astropy.utils.iers.TIME_BEYOND_IERS_RANGE

Notes

In normal usage, UT1-UTC differences are calculated automatically on the first instance ut1 is needed.

Examples

To check in code whether any times are before the IERS table range:

>>> from astropy.utils.iers import TIME_BEFORE_IERS_RANGE
>>> t = Time(['1961-01-01', '2000-01-01'], scale='utc')
>>> delta, status = t.get_delta_ut1_utc(return_status=True)
>>> status == TIME_BEFORE_IERS_RANGE
array([ True, False]...)
light_travel_time(skycoord, kind='barycentric', location=None, ephemeris=None) [edit on github]

Light travel time correction to the barycentre or heliocentre.

The frame transformations used to calculate the location of the solar system barycentre and the heliocentre rely on the erfa routine epv00, which is consistent with the JPL DE405 ephemeris to an accuracy of 11.2 km, corresponding to a light travel time of 4 microseconds.

The routine assumes the source(s) are at large distance, i.e., neglects finite-distance effects.

Parameters:
skycoord : SkyCoord

The sky location to calculate the correction for.

kind : str, optional

'barycentric' (default) or 'heliocentric'

location : EarthLocation, optional

The location of the observatory to calculate the correction for. If no location is given, the location attribute of the Time object is used

ephemeris : str, optional

Solar system ephemeris to use (e.g., ‘builtin’, ‘jpl’). By default, use the one set with astropy.coordinates.solar_system_ephemeris.set. For more information, see solar_system_ephemeris.

Returns:
time_offset : TimeDelta

The time offset between the barycentre or Heliocentre and Earth, in TDB seconds. Should be added to the original time to get the time in the Solar system barycentre or the Heliocentre. Also, the time conversion to BJD will then include the relativistic correction as well.

max(axis=None, out=None, keepdims=False) [edit on github]

Maximum along a given axis.

This is similar to max(), but adapted to ensure that the full precision given by the two doubles jd1 and jd2 is used, and that corresponding attributes are copied.

Note that the out argument is present only for compatibility with np.max; since Time instances are immutable, it is not possible to have an actual out to store the result in.

min(axis=None, out=None, keepdims=False) [edit on github]

Minimum along a given axis.

This is similar to min(), but adapted to ensure that the full precision given by the two doubles jd1 and jd2 is used, and that corresponding attributes are copied.

Note that the out argument is present only for compatibility with np.min; since Time instances are immutable, it is not possible to have an actual out to store the result in.

classmethod now() [edit on github]

Creates a new object corresponding to the instant in time this method is called.

Note

“Now” is determined using the utcnow function, so its accuracy and precision is determined by that function. Generally that means it is set by the accuracy of your system clock.

Returns:
nowtime

A new Time object (or a subclass of Time if this is called from such a subclass) at the current time.

ptp(axis=None, out=None, keepdims=False) [edit on github]

Peak to peak (maximum - minimum) along a given axis.

This is similar to ptp(), but adapted to ensure that the full precision given by the two doubles jd1 and jd2 is used.

Note that the out argument is present only for compatibility with ptp; since Time instances are immutable, it is not possible to have an actual out to store the result in.

ravel(*args, **kwargs) [edit on github]

Return an instance with the array collapsed into one dimension.

Parameters are as for ravel(). Note that it is not always possible to unravel an array without copying the data. If you want an error to be raise if the data is copied, you should should assign shape (-1,) to the shape attribute.

replicate(*args, **kwargs)[source] [edit on github]

Return a replica of the Time object, optionally changing the format.

If format is supplied then the time format of the returned Time object will be set accordingly, otherwise it will be unchanged from the original.

If copy is set to True then a full copy of the internal time arrays will be made. By default the replica will use a reference to the original arrays when possible to save memory. The internal time arrays are normally not changeable by the user so in most cases it should not be necessary to set copy to True.

The convenience method copy() is available in which copy is True by default.

Parameters:
format : str, optional

Time format of the replica.

copy : bool, optional

Return a true copy instead of using references where possible.

Returns:
tm : Time object

Replica of this object

reshape(*args, **kwargs) [edit on github]

Returns an instance containing the same data with a new shape.

Parameters are as for reshape(). Note that it is not always possible to change the shape of an array without copying the data (see reshape() documentation). If you want an error to be raise if the data is copied, you should assign the new shape to the shape attribute (note: this may not be implemented for all classes using ShapedLikeNDArray).

sidereal_time(kind, longitude=None, model=None) [edit on github]

Calculate sidereal time.

Parameters:
kind : str

'mean' or 'apparent', i.e., accounting for precession only, or also for nutation.

longitude : Quantity, str, or None; optional

The longitude on the Earth at which to compute the sidereal time. Can be given as a Quantity with angular units (or an Angle or Longitude), or as a name of an observatory (currently, only 'greenwich' is supported, equivalent to 0 deg). If None (default), the lon attribute of the Time object is used.

model : str or None; optional

Precession (and nutation) model to use. The available ones are: - apparent: [‘IAU1994’, ‘IAU2000A’, ‘IAU2000B’, ‘IAU2006A’] - mean: [‘IAU1982’, ‘IAU2000’, ‘IAU2006’] If None (default), the last (most recent) one from the appropriate list above is used.

Returns:
sidereal time : Longitude

Sidereal time as a quantity with units of hourangle

sort(axis=-1) [edit on github]

Return a copy sorted along the specified axis.

This is similar to sort(), but internally uses indexing with lexsort() to ensure that the full precision given by the two doubles jd1 and jd2 is kept, and that corresponding attributes are properly sorted and copied as well.

Parameters:
axis : int or None

Axis to be sorted. If None, the flattened array is sorted. By default, sort over the last axis.

squeeze(*args, **kwargs) [edit on github]

Return an instance with single-dimensional shape entries removed

Parameters are as for squeeze(). All internal data are views of the data of the original.

strftime(format_spec) [edit on github]

Convert Time to a string or a numpy.array of strings according to a format specification. See time.strftime documentation for format specification.

Parameters:
format_spec : string

Format definition of return string.

Returns:
formatted : string, numpy.array

String or numpy.array of strings formatted according to the given format string.

classmethod strptime(time_string, format_string, **kwargs) [edit on github]

Parse a string to a Time according to a format specification. See time.strptime documentation for format specification.

>>> Time.strptime('2012-Jun-30 23:59:60', '%Y-%b-%d %H:%M:%S')
<Time object: scale='utc' format='isot' value=2012-06-30T23:59:60.000>
Parameters:
time_string : string, sequence, ndarray

Objects containing time data of type string

format_string : string

String specifying format of time_string.

kwargs : dict

Any keyword arguments for Time. If the format keyword argument is present, this will be used as the Time format.

Returns:
time_obj : Time

A new Time object corresponding to the input time_string.

swapaxes(*args, **kwargs) [edit on github]

Return an instance with the given axes interchanged.

Parameters are as for swapaxes(): axis1, axis2. All internal data are views of the data of the original.

take(indices, axis=None, mode='raise') [edit on github]

Return a new instance formed from the elements at the given indices.

Parameters are as for take(), except that, obviously, no output array can be given.

to(*args, **kwargs)[source] [edit on github]
to_datetime()[source] [edit on github]

Convert to datetime.timedelta object.

transpose(*args, **kwargs) [edit on github]

Return an instance with the data transposed.

Parameters are as for transpose(). All internal data are views of the data of the original.