Time¶
-
class
astropy.time.
Time
(val, val2=None, format=None, scale=None, precision=None, in_subfmt=None, out_subfmt=None, location=None, copy=False)[source]¶ Bases:
astropy.utils.misc.ShapedLikeNDArray
Represent and manipulate times and dates for astronomy.
A
Time
object is initialized with one or more times in theval
argument. The input times inval
must conform to the specifiedformat
and must correspond to the specified timescale
. The optionalval2
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(Time.FORMATS) ['jd', 'mjd', 'decimalyear', 'unix', 'unix_tai', 'cxcsec', 'gps', 'plot_date', 'stardate', 'datetime', 'ymdhms', 'iso', 'isot', 'yday', 'datetime64', 'fits', 'byear', 'jyear', 'byear_str', 'jyear_str']
See also: http://docs.astropy.org/en/stable/time/
- Parameters
- valsequence, ndarray, number, str, bytes, or
Time
object Value(s) to initialize the time or times. Bytes are decoded as ascii.
- val2sequence, ndarray, or number; optional
Value(s) to initialize the time or times. Only used for numerical input, to help preserve precision.
- formatstr, optional
Format of input value(s)
- scalestr, optional
Time scale of input value(s), must be one of the following: (‘tai’, ‘tcb’, ‘tcg’, ‘tdb’, ‘tt’, ‘ut1’, ‘utc’)
- precisionint, optional
Digits of precision in string representation of time
- in_subfmtstr, optional
Unix glob to select subformats for parsing input times
- out_subfmtstr, optional
Unix glob to select subformat for outputting times
- location
EarthLocation
or tuple, optional If given as an tuple, it should be able to initialize an an EarthLocation instance, i.e., either contain 3 items with units of length for geocentric coordinates, or contain a longitude, latitude, and an optional height for geodetic coordinates. Can be a single location, or one for each input time.
- copybool, optional
Make a copy of the input values
- valsequence, ndarray, number, str, bytes, or
Attributes Summary
Dict of time formats
List of time scales
Return an instance with the data transposed.
Return the cache associated with this instance.
TDB - TT time scale offset
UT1 - UTC time scale offset
Get or set time format.
Unix wildcard pattern to select subformats for parsing string input times.
info
([option, out])Container for meta information like name, description, format.
First of the two doubles that internally store time value(s) in JD.
Second of the two doubles that internally store time value(s) in JD.
The number of dimensions of the instance and underlying arrays.
Unix wildcard pattern to select subformats for outputting times.
Decimal precision when outputting seconds as floating point (int value between 0 and 9 inclusive).
Time scale
The shape of the time instances.
The size of the object, as calculated from its shape.
Time value(s) in current format
Methods Summary
argmax
(self[, axis, out])Return indices of the maximum values along the given axis.
argmin
(self[, axis, out])Return indices of the minimum values along the given axis.
argsort
(self[, axis])Returns the indices that would sort the time array.
copy
(self[, format])Return a fully independent copy the Time object, optionally changing the format.
diagonal
(self, *args, **kwargs)Return an instance with the specified diagonals.
flatten
(self, *args, **kwargs)Return a copy with the array collapsed into one dimension.
get_delta_ut1_utc
(self[, iers_table, …])Find UT1 - UTC differences by interpolating in IERS Table.
insert
(self, obj, values[, axis])Insert values before the given indices in the column and return a new
Time
orTimeDelta
object.light_travel_time
(self, skycoord[, kind, …])Light travel time correction to the barycentre or heliocentre.
max
(self[, axis, out, keepdims])Maximum along a given axis.
min
(self[, axis, out, keepdims])Minimum along a given axis.
now
()Creates a new object corresponding to the instant in time this method is called.
ptp
(self[, axis, out, keepdims])Peak to peak (maximum - minimum) along a given axis.
ravel
(self, *args, **kwargs)Return an instance with the array collapsed into one dimension.
replicate
(self[, format, copy])Return a replica of the Time object, optionally changing the format.
reshape
(self, *args, **kwargs)Returns an instance containing the same data with a new shape.
sidereal_time
(self, kind[, longitude, model])Calculate sidereal time.
sort
(self[, axis])Return a copy sorted along the specified axis.
squeeze
(self, *args, **kwargs)Return an instance with single-dimensional shape entries removed
strftime
(self, 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
(self, *args, **kwargs)Return an instance with the given axes interchanged.
take
(self, indices[, axis, mode])Return a new instance formed from the elements at the given indices.
to_datetime
(self[, timezone])Convert to (potentially timezone-aware)
datetime
object.to_value
(self, format[, subfmt])Get time values expressed in specified output format.
transpose
(self, *args, **kwargs)Return an instance with the data transposed.
Attributes Documentation
-
FORMATS
= {'byear': <class 'astropy.time.formats.TimeBesselianEpoch'>, 'byear_str': <class 'astropy.time.formats.TimeBesselianEpochString'>, 'cxcsec': <class 'astropy.time.formats.TimeCxcSec'>, 'datetime': <class 'astropy.time.formats.TimeDatetime'>, 'datetime64': <class 'astropy.time.formats.TimeDatetime64'>, 'decimalyear': <class 'astropy.time.formats.TimeDecimalYear'>, 'fits': <class 'astropy.time.formats.TimeFITS'>, 'gps': <class 'astropy.time.formats.TimeGPS'>, 'iso': <class 'astropy.time.formats.TimeISO'>, 'isot': <class 'astropy.time.formats.TimeISOT'>, 'jd': <class 'astropy.time.formats.TimeJD'>, 'jyear': <class 'astropy.time.formats.TimeJulianEpoch'>, 'jyear_str': <class 'astropy.time.formats.TimeJulianEpochString'>, 'mjd': <class 'astropy.time.formats.TimeMJD'>, 'plot_date': <class 'astropy.time.formats.TimePlotDate'>, 'stardate': <class 'astropy.time.formats.TimeStardate'>, 'unix': <class 'astropy.time.formats.TimeUnix'>, 'unix_tai': <class 'astropy.time.formats.TimeUnixTai'>, 'yday': <class 'astropy.time.formats.TimeYearDayTime'>, 'ymdhms': <class 'astropy.time.formats.TimeYMDHMS'>}¶ Dict of time formats
-
SCALES
= ('tai', 'tcb', 'tcg', 'tdb', 'tt', 'ut1', 'utc', 'local')¶ List of time 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
¶ TDB - TT time scale offset
-
delta_ut1_utc
¶ UT1 - UTC time scale offset
-
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 theTime
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', 'unix_tai', 'cxcsec', 'gps', 'plot_date', 'stardate', 'datetime', 'ymdhms', 'iso', 'isot', 'yday', 'datetime64', 'fits', 'byear', 'jyear', 'byear_str', 'jyear_str']
-
in_subfmt
¶ Unix wildcard pattern to select subformats for parsing string input times.
-
info
(option='attributes', out='')¶ Container for meta information like name, description, format. This is required when the object is used as a mixin column within a table, but can be used as a general way to store meta information.
-
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 thereshape
method.- Raises
- AttributeError
If the shape of the
jd1
,jd2
,location
,delta_ut1_utc
, ordelta_tdb_tt
attributes cannot be changed without the arrays being copied. For these cases, use theTime.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
(self, axis=None, out=None)[source]¶ 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 doublesjd1
andjd2
is used. Seeargmax()
for detailed documentation.
-
argmin
(self, axis=None, out=None)[source]¶ 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 doublesjd1
andjd2
is used. Seeargmin()
for detailed documentation.
-
argsort
(self, axis=- 1)[source]¶ 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 doublesjd1
andjd2
is used, and that corresponding attributes are copied. Internally, it useslexsort()
, and hence no sort method can be chosen.
-
copy
(self, format=None)[source]¶ 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
- formatstr, optional
Time format of the copy.
- Returns
- tmTime object
Copy of this object
-
diagonal
(self, *args, **kwargs)¶ Return an instance with the specified diagonals.
Parameters are as for
diagonal()
. All internal data are views of the data of the original.
-
flatten
(self, *args, **kwargs)¶ Return a copy with the array collapsed into one dimension.
Parameters are as for
flatten()
.
-
get_delta_ut1_utc
(self, iers_table=None, return_status=False)[source]¶ Find UT1 - UTC differences by interpolating in IERS Table.
- Parameters
- iers_table
IERS
table, optional Table containing UT1-UTC differences from IERS Bulletins A and/or B. Default:
earth_orientation_table
(which in turn defaults to the combined version provided byIERS_Auto
).- return_statusbool
Whether to return status values. If
False
(default), iers raisesIndexError
if any time is out of the range covered by the IERS table.
- iers_table
- Returns
- ut1_utcfloat or float array
UT1-UTC, interpolated in IERS Table
- statusint 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]...)
-
insert
(self, obj, values, axis=0)[source]¶ Insert values before the given indices in the column and return a new
Time
orTimeDelta
object.The values to be inserted must conform to the rules for in-place setting of
Time
objects (seeGet and set values
in theTime
documentation).The API signature matches the
np.insert
API, but is more limited. The specification of insert indexobj
must be a single integer, and theaxis
must be0
for simple row insertion before the index.- Parameters
- objint
Integer index before which
values
is inserted.- valuesarray_like
Value(s) to insert. If the type of
values
is different from that of quantity,values
is converted to the matching type.- axisint, optional
Axis along which to insert
values
. Default is 0, which is the only allowed value and will insert a row.
- Returns
- out
Time
subclass New time object with inserted value(s)
- out
-
light_travel_time
(self, skycoord, kind='barycentric', location=None, ephemeris=None)[source]¶ 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.
- kindstr, 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- ephemerisstr, 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, seesolar_system_ephemeris
.
- skycoord
- 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.
- time_offset
-
max
(self, axis=None, out=None, keepdims=False)[source]¶ Maximum along a given axis.
This is similar to
max()
, but adapted to ensure that the full precision given by the two doublesjd1
andjd2
is used, and that corresponding attributes are copied.Note that the
out
argument is present only for compatibility withnp.max
; sinceTime
instances are immutable, it is not possible to have an actualout
to store the result in.
-
min
(self, axis=None, out=None, keepdims=False)[source]¶ Minimum along a given axis.
This is similar to
min()
, but adapted to ensure that the full precision given by the two doublesjd1
andjd2
is used, and that corresponding attributes are copied.Note that the
out
argument is present only for compatibility withnp.min
; sinceTime
instances are immutable, it is not possible to have an actualout
to store the result in.
-
classmethod
now
()[source]¶ 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.
-
ptp
(self, axis=None, out=None, keepdims=False)[source]¶ 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 doublesjd1
andjd2
is used.Note that the
out
argument is present only for compatibility withptp
; sinceTime
instances are immutable, it is not possible to have an actualout
to store the result in.
-
ravel
(self, *args, **kwargs)¶ 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
(self, format=None, copy=False)[source]¶ 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 toTrue
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 setcopy
toTrue
.The convenience method copy() is available in which
copy
isTrue
by default.- Parameters
- formatstr, optional
Time format of the replica.
- copybool, optional
Return a true copy instead of using references where possible.
- Returns
- tmTime object
Replica of this object
-
reshape
(self, *args, **kwargs)¶ 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 (seereshape()
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 usingShapedLikeNDArray
).
-
sidereal_time
(self, kind, longitude=None, model=None)[source]¶ Calculate sidereal time.
- Parameters
- kindstr
'mean'
or'apparent'
, i.e., accounting for precession only, or also for nutation.- longitude
Quantity
,str
, orNone
; optional The longitude on the Earth at which to compute the sidereal time. Can be given as a
Quantity
with angular units (or anAngle
orLongitude
), or as a name of an observatory (currently, only'greenwich'
is supported, equivalent to 0 deg). IfNone
(default), thelon
attribute of the Time object is used.- modelstr 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
- sidereal time
-
sort
(self, axis=- 1)[source]¶ Return a copy sorted along the specified axis.
This is similar to
sort()
, but internally uses indexing withlexsort()
to ensure that the full precision given by the two doublesjd1
andjd2
is kept, and that corresponding attributes are properly sorted and copied as well.- Parameters
- axisint or None
Axis to be sorted. If
None
, the flattened array is sorted. By default, sort over the last axis.
-
squeeze
(self, *args, **kwargs)¶ 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
(self, format_spec)[source]¶ 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_specstr
Format definition of return string.
- Returns
- formattedstr or numpy.array
String or numpy.array of strings formatted according to the given format string.
-
classmethod
strptime
(time_string, format_string, **kwargs)[source]¶ 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_stringstr, sequence, or ndarray
Objects containing time data of type string
- format_stringstr
String specifying format of time_string.
- kwargsdict
Any keyword arguments for
Time
. If theformat
keyword argument is present, this will be used as the Time format.
- Returns
-
swapaxes
(self, *args, **kwargs)¶ 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
(self, indices, axis=None, mode='raise')¶ 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_datetime
(self, timezone=None)[source]¶ Convert to (potentially timezone-aware)
datetime
object.If
timezone
is notNone
, return a timezone-aware datetime object.
-
to_value
(self, format, subfmt='*')[source]¶ Get time values expressed in specified output format.
This method allows representing the
Time
object in the desired outputformat
and optional sub-formatsubfmt
. Available built-in formats includejd
,mjd
,iso
, and so forth. Each format can have its own sub-formatsFor built-in numerical formats like
jd
orunix
,subfmt
can be one of ‘float’, ‘long’, ‘decimal’, ‘str’, or ‘bytes’. Here, ‘long’ usesnumpy.longdouble
for somewhat enhanced precision (with the enhancement depending on platform), and ‘decimal’decimal.Decimal
for full precision. For ‘str’ and ‘bytes’, the number of digits is also chosen such that time values are represented accurately.For built-in date-like string formats, one of ‘date_hms’, ‘date_hm’, or ‘date’ (or ‘longdate_hms’, etc., for 5-digit years in
TimeFITS
). For sub-formats including seconds, the number of digits used for the fractional seconds is as set byprecision
.- Parameters
- formatstr
The format in which one wants the time values. Default: the current format.
- subfmtstr or
None
, optional Value or wildcard pattern to select the sub-format in which the values should be given. The default of ‘*’ picks the first available for a given format, i.e., ‘float’ or ‘date_hms’. If
None
, use the instance’sout_subfmt
.
-
transpose
(self, *args, **kwargs)¶ Return an instance with the data transposed.
Parameters are as for
transpose()
. All internal data are views of the data of the original.