# 时间和日期 (`astropy.time` ）¶

## 介绍¶

1

Shewchuk，1997，离散与计算几何18（3）：305-363

## 入门¶

### 实例¶

```>>> 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]
<Time object: scale='utc' format='isot' value=2010-01-01T00:00:00.000>
```

```>>> t = Time(times, format='isot')
```

```>>> t = Time(times)
```

```>>> t.jd
array([2451179.50000143, 2455197.5       ])
>>> t.mjd
array([51179.00000143, 55197.        ])
```

```>>> t.to_value('mjd', 'long')
array([51179.00000143, 55197.        ], dtype=float128)
```

```>>> t.format = 'fits'
>>> t
<Time object: scale='utc' format='fits' value=['1999-01-01T00:00:00.123'
'2010-01-01T00:00:00.000']>
>>> t.format = 'isot'
```

```>>> t2 = t.tt
>>> t2
<Time object: scale='tt' format='isot' value=['1999-01-01T00:01:04.307' '2010-01-01T00:01:06.184']>
>>> t2.jd
array([2451179.5007443 , 2455197.50076602])
```

```>>> print(t2.fits)
['1999-01-01T00:01:04.307' '2010-01-01T00:01:06.184']
```

```>>> 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']
```

```>>> t2[0] = np.ma.masked  # Declare that first time is missing or invalid
>>> print(t2)
[-- '2014-12-25T00:00:00.000']
```

```>>> dt = t[1] - t[0]
>>> dt
<TimeDelta object: scale='tai' format='jd' value=4018.00002172>
```

```>>> import numpy as np
>>> t[0] + dt * np.linspace(0.,1.,12)
<Time object: scale='utc' format='isot' value=['1999-01-01T00:00:00.123' '2000-01-01T06:32:43.930'
'2000-12-31T13:05:27.737' '2001-12-31T19:38:11.544'
'2003-01-01T02:10:55.351' '2004-01-01T08:43:39.158'
'2004-12-31T15:16:22.965' '2005-12-31T21:49:06.772'
'2007-01-01T04:21:49.579' '2008-01-01T10:54:33.386'
'2008-12-31T17:27:17.193' '2010-01-01T00:00:00.000']>
```
```>>> t.sidereal_time('apparent', 'greenwich')
<Longitude [6.68050179, 6.70281947] hourangle>
```

## 使用 `astropy.time`¶

### 时间对象基础¶

`astropy.time` 以时间为单位表示的时间与时间的关系。在“日期”和“时间”之间没有区别，因为这两个概念（在一般用法中的松散定义）只是时间上某个时刻的不同表示。

#### 时间格式¶

`TimeBesselianEpoch`

1950.0

byear_str

`TimeBesselianEpochString`

'B1950.0'

cxcsec公司

`TimeCxcSec`

63072064.184

`TimeDatetime`

`TimeDecimalYear`

2000.45

`TimeFITS`

‘2000-01-01T00:00:00.000’

`TimeGPS`

630720013.0

`TimeISO`

'2000-01-01 00:00:00.000'

isot公司

`TimeISOT`

‘2000-01-01T00:00:00.000’

`TimeJD`

2451544.5

jyear公司

`TimeJulianEpoch`

2000.0

jyear_str

`TimeJulianEpochString`

'J2000.0'

`TimeMJD`

51544.0

plot_date

`TimePlotDate`

730120.0003703703

UNIX

`TimeUnix`

946684800.0

unix_tai

`TimeUnixTai`

946684800.0

`TimeYearDayTime`

2000:001:00:00:00.000

`TimeYMDHMS`

{'year'：2010，'月'：3，'日'：1}

`TimeDatetime64`

np.日期时间64（'2000-01-01T01:01:01'）

2

Rots et al. 2015, A&A 574:A36

##### 更改格式¶

```>>> t = Time('2000-01-02')
>>> t.format = 'jd'
>>> t
<Time object: scale='utc' format='jd' value=2451545.5>
```

```>>> t = Time('2000-01-02', format='fits', out_subfmt='longdate')
>>> t.value
'+02000-01-02'
>>> t.format = 'iso'
>>> t.out_subfmt
u'*'
>>> t.format = 'fits'
>>> t.value
'2000-01-02T00:00:00.000'
```
##### 子格式¶

`iso``fits``yday` 格式：

`iso`

date_hms

2001-01-02 03:04:05.678

`iso`

date_hm

2001-01-02 03:04

`iso`

2001-01-02

`fits`

date_hms

2001-01-02T03:04:05.678

`fits`

longdate_hms

+02001-01-02T03:04:05.678

`fits`

+02001-01-02

`yday`

date_hms

2001:032:03:04:05.678

`yday`

date_hm

2001:032:03:04

`yday`

2001:032

```>>> tm = Time('51544.000000000000001', format='mjd')  # String input
>>> tm.mjd  # float64 output loses last digit but Decimal gets it
51544.0
>>> tm.to_value('mjd', subfmt='decimal')
Decimal('51544.00000000000000099920072216264')
>>> tm.to_value('mjd', subfmt='str')
'51544.000000000000001'
```

`byear`

`cxcsec`

`datetime64`

`decimalyear`

`fits`

`gps`

`iso`

`isot`

`jd`

`jyear`

`mjd`

`plot_date`

`unix`

`unix_tai`

`yday`

`jd`

`sec`

##### 历元格式的时间¶

`cxcsec`

TT

`1998-01-01 00:00:00`

`unix`

UTC

`1970-01-01 00:00:00`

`unix_tai`

TAI

`1970-01-01 00:00:08`

`gps`

TAI

`1980-01-06 00:00:19`

#### 时间尺度¶

```>>> Time.SCALES
('tai', 'tcb', 'tcg', 'tdb', 'tt', 'ut1', 'utc', 'local')
```

tcb公司

tcg公司

tdb公司

tt

ut1型

UTC

3

4

SOFA 时间刻度和日历工具 (PDF)

#### 标量或数组¶

A `Time` 对象可以保存单个时间值或时间值数组。区别完全是由输入时间的形式决定的。如果 `Time` 对象包含一个值，则任何格式输出都将是一个标量值，对于数组也是如此。

##### 例子¶

```>>> from astropy.time import Time
>>> t = Time(100.0, format='mjd')
>>> t.jd
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]
<Time object: scale='utc' format='mjd' value=300.0>
>>> t = Time(np.arange(50000., 50003.)[:, np.newaxis],
...          np.arange(0., 1., 0.5), format='mjd')
>>> t
<Time object: scale='utc' format='mjd' value=[[50000.  50000.5]
[50001.  50001.5]
[50002.  50002.5]]>
>>> t[0]
<Time object: scale='utc' format='mjd' value=[50000.  50000.5]>
```

#### NumPy方法的类比和适用的NumPy函数¶

##### 实例¶

```.. doctest-requires:: numpy>=1.17
```
```>>> t.reshape(2, 3)
<Time object: scale='utc' format='mjd' value=[[50000.  50000.5 50001. ]
[50001.5 50002.  50002.5]]>
>>> t.T
<Time object: scale='utc' format='mjd' value=[[50000.  50001.  50002. ]
[50000.5 50001.5 50002.5]]>
>>> np.roll(t, 1, axis=0)
<Time object: scale='utc' format='mjd' value=[[50002.  50002.5]
[50000.  50000.5]
[50001.  50001.5]]>
```

```>> t.max()
<Time object: scale='utc' format='mjd' value=50002.5>
>> t.ptp(axis=0)  # doctest: +FLOAT_CMP
<TimeDelta object: scale='tai' format='jd' value=[2. 2.]>
```

#### 推断输入格式¶

##### 例子¶

```>>> from datetime import datetime
>>> t = Time(datetime(2010, 1, 2, 1, 2, 3))
>>> t.format
'datetime'
>>> t = Time('2010-01-02 01:02:03')
>>> t.format
'iso'
```

#### 内部代表¶

```>>> t = Time('2010-01-01 00:00:00', scale='utc')
>>> t.jd1, t.jd2
(2455198.0, -0.5)
>>> t2 = t.tai
>>> t2.jd1, t2.jd2
(2455198., -0.49960648148148146)
```

### 创建时间对象¶

valnumpy ndarray、list、str或number

val2numpy ndarray、list、str或number；可选

format可选的STR

scale可选的STR

precision0到9之间的整数（包括0和9）

in_subfmtSTR

Unix glob选择用于分析输入时间的子格式。

out_subfmtSTR

Unix glob为输出时间选择子格式。

#### 瓦尔¶

```>>> t1 = Time(50100.0, scale='tt', format='mjd')
>>> t2 = Time('2010-01-01 00:00:00', scale='utc')
```

```>>> Time([t1, t2])
<Time object: scale='tt' format='mjd' value=[50100. 55197.00076602]>
```

#### 瓦尔2¶

```>>> t = Time(100.0, 0.000001, format='mjd', scale='tt')
>>> t.jd, t.jd1, t.jd2
(2400100.500001, 2400101.0, -0.499999)
```

#### 规模¶

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.

#### 精度¶

```>>> t = Time('B1950.0', precision=3)
>>> t.byear_str
'B1950.000'
>>> t.precision = 0
>>> t.byear_str
'B1950'
```

#### in_subfmt¶

```>>> Time(['2000:001', '2000:002:03:04', '2001:003:04:05:06.789'])
<Time object: scale='utc' format='yday'
value=['2000:001:00:00:00.000' '2000:002:03:04:00.000' '2001:003:04:05:06.789']>
```

```>>> 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']
```

#### out_subfmt¶

```>>> Time('2000-01-01 02:03:04', out_subfmt='date').iso
'2000-01-01'
>>> Time('2000-01-01 02:03:04', out_subfmt='date_hms').iso
'2000-01-01 02:03:04.000'
>>> Time('2000-01-01 02:03:04', out_subfmt='date*').iso
'2000-01-01 02:03:04.000'
>>> Time('50814.123456789012345', format='mjd', out_subfmt='str').mjd
'50814.123456789012345'
```

#### 位置¶

```>>> t = Time('2001-03-22 00:01:44.732327132980', scale='utc',
...          location=('120d', '40d'))
>>> t.sidereal_time('apparent', 'greenwich')
<Longitude 12. hourangle>
>>> t.sidereal_time('apparent')
<Longitude 20. hourangle>
```

#### 获取当前时间¶

```>>> nt = Time.now()
>>> ut = Time(datetime.utcnow(), scale='utc')
```

#### 基于C的快速数据串解析器¶

C解析器比基于Python的解析器（它依赖于 `strptime` ). 特别是月份或一年中的某一天之类的字段必须始终具有固定数量的ASCII数字。作为一个例子，Python解析器将接受 `2000-1-2T3:04:5.23` 而C解析器需要 `2000-01-02T03:04:05.23`

```>>> 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
```

```>>> 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
```

### 使用时间对象¶

#### 获取和设置值¶

##### 实例¶

```>>> t = Time(['2001:020', '2001:040', '2001:060', '2001:080'],
...          out_subfmt='date')
>>> print(t[1])
2001:040
>>> print(t[1:])
['2001:040' '2001:060' '2001:080']
>>> print(t[[2, 0]])
['2001:060' '2001:020']
```

```>>> t = Time(['2001:020', '2001:040', '2001:060', '2001:080'],
...          out_subfmt='date')
>>> t[1] = '2010:001'
>>> print(t)
['2001:020' '2010:001' '2001:060' '2001:080']
>>> t[[2, 0]] = '1990:123'
>>> print(t)
['1990:123' '2010:001' '1990:123' '2001:080']
```

• 标量字符串值或字符串值数组，其中每个值都是有效的时间格式，可以自动分析并用于创建 `Time` 对象。

• 值或值数组，其中每个值都具有相同的值 `format` 作为 `Time` 正在设置的对象。例如，浮动或 `numpy` 对象的浮点数组 `format='unix'` .

• `Time` 具有相同的对象 `location` （但是 `scale``format` 不必相同）。右侧值将被转换为时间 `scale` 比赛。

#### 缺少值¶

##### 例子¶

```>>> t = Time(['2001:020', '2001:040', '2001:060', '2001:080'],
...          out_subfmt='date')
>>> print(t)
['2001:020' '2001:040' -- '2001:080']
```

```>>> t.unix
masked_array(data = [979948800.0 981676800.0 -- 985132800.0],
mask = [False False  True False],
fill_value = 1e+20)
```

```>>> t.mask
array([False, False,  True, False]...)
```

#### 获取表示¶

a的表示 `Time` 通过获取与格式名对应的object属性，可以使用特定格式的对象。可用格式名的列表在 time format 部分。

```>>> t = Time('2010-01-01 00:00:00', format='iso', scale='utc')
>>> t.jd        # JD representation of time in current scale (UTC)
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)
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()
```

#### 转换时间刻度¶

##### 实例¶

```>>> t = Time('2010-01-01 00:00:00', format='iso', scale='utc')
>>> t.tt        # TT scale
<Time object: scale='tt' format='iso' value=2010-01-01 00:01:06.184>
>>> t.tai
<Time object: scale='tai' format='iso' value=2010-01-01 00:00:34.000>
```

Time Object Basics 剖面图，a `Time` 对象只能通过显式设置其某些元素来更改。因此，更改时间刻度的过程首先制作原始对象的副本，然后将副本中的内部时间值转换为新的时间刻度。新的 `Time` 对象由属性access返回。

#### 高速缓存¶

```>>> 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
```

```>>> del t.cache

>>> time x = t.tt
CPU times: user 263 ms, sys: 4.02 ms, total: 267 ms
Wall time: 267 ms
```

```>>> 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.
```

##### 转换偏移量¶

```>>> 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'
```

`delta_ut1_utc` 属性未显式设置，将使用IERS值（第一次开始下载几个Mb的文件）。有关如何在中使用IER值的详细信息 `astropy` 时间和坐标，以及要了解如何控制自动下载，请参阅 IERS数据访问 (astropy.utils.iers ） . 下面的示例说明如何转换为 `UT1` 随着自动下载功能的扩展：

```>>> t = Time('2016:001')
>>> t.ut1
|==================================================================| 3.0M/3.0M (100.00%)         6s
<Time object: scale='ut1' format='yday' value=2016:001:00:00:00.082>
```

###### 例子¶

```>>> import astropy.units as u
>>> t = Time('2006-01-15 21:24:37.5', format='iso', scale='utc',
...          location=(-155.933222*u.deg, 19.48125*u.deg))
>>> t.utc.iso
'2006-01-15 21:24:37.500'
>>> t.ut1.iso
'2006-01-15 21:24:37.834'
>>> t.tai.iso
'2006-01-15 21:25:10.500'
>>> t.tt.iso
'2006-01-15 21:25:42.684'
>>> t.tcg.iso
'2006-01-15 21:25:43.323'
>>> t.tdb.iso
'2006-01-15 21:25:42.684'
>>> t.tcb.iso
'2006-01-15 21:25:56.894'
```

#### 打印时间数组¶

```>>> many_times = np.arange(1000)
>>> t = Time(many_times, format='cxcsec')
>>> with np.printoptions(threshold=10):
...     print(repr(t))
...     print(t.iso)
<Time object: scale='tt' format='cxcsec' value=[  0.   1.   2. ... 997. 998. 999.]>
['1998-01-01 00:00:00.000' '1998-01-01 00:00:01.000'
'1998-01-01 00:00:02.000' ... '1998-01-01 00:16:37.000'
'1998-01-01 00:16:38.000' '1998-01-01 00:16:39.000']
```

### 实时¶

#### 例子¶

```>>> t = Time('2006-01-15 21:24:37.5', scale='utc', location=('120d', '45d'))
>>> t.sidereal_time('mean')
<Longitude 13.08952187 hourangle>
>>> t.sidereal_time('apparent')
<Longitude 13.08950368 hourangle>
>>> t.sidereal_time('apparent', 'greenwich')
<Longitude 5.08950368 hourangle>
>>> t.sidereal_time('apparent', '-90d')
<Longitude 23.08950368 hourangle>
>>> t.sidereal_time('apparent', '-90d', 'IAU1994')
<Longitude 23.08950365 hourangle>
```

### 时间三角洲¶

`TimeDeltaSec`

`TimeDeltaJD`

`TimeDeltaDatetime`

#### 实例¶

```>>> t1 = Time('2010-01-01 00:00:00')
>>> t2 = Time('2010-02-01 00:00:00')
>>> dt = t2 - t1  # Difference between two Times
>>> dt
<TimeDelta object: scale='tai' format='jd' value=31.0>
>>> dt.sec
2678400.0

>>> from astropy.time import TimeDelta
>>> dt2 = TimeDelta(50.0, format='sec')
>>> t3 = t2 + dt2  # Add a TimeDelta to a Time
>>> t3.iso
'2010-02-01 00:00:50.000'

>>> t2 - dt2  # Subtract a TimeDelta from a Time
<Time object: scale='utc' format='iso' value=2010-01-31 23:59:10.000>

>>> dt + dt2
<TimeDelta object: scale='tai' format='jd' value=31.0005787037>

>>> import numpy as np
>>> t1 + dt * np.linspace(0, 1, 5)
<Time object: scale='utc' format='iso' value=['2010-01-01 00:00:00.000'
'2010-01-08 18:00:00.000' '2010-01-16 12:00:00.000' '2010-01-24 06:00:00.000'
'2010-02-01 00:00:00.000']>
```

```>>> dt.to_value(u.hr)
744.0
>>> dt.to_value('jd', 'str')
'31.0'
```

#### 时间三角洲的时间尺度¶

##### 实例¶

```>>> t1 = Time('2010-01-01 00:00:00', scale='tcg')
>>> t2 = Time('2011-01-01 00:00:00', scale='tcg')
>>> dt = t2 - t1
>>> dt
<TimeDelta object: scale='tcg' format='jd' value=365.0>
```

```>>> t2 + dt
<Time object: scale='tcg' format='iso' value=2012-01-01 00:00:00.000>
>>> t2.tai
<Time object: scale='tai' format='iso' value=2010-12-31 23:59:27.068>
>>> t2.tai + dt
<Time object: scale='tai' format='iso' value=2011-12-31 23:59:27.046>
```

`TimeDelta` 我不需要把时间转换成不同的比例尺

```>>> dt.tt
<TimeDelta object: scale='tt' format='jd' value=364.999999746>
>>> dt.tdb
Traceback (most recent call last):
...
ScaleValueError: Cannot convert TimeDelta with scale 'tcg' to scale 'tdb'
```

`TimeDelta` 对象也可以具有未定义的比例，在这种情况下，假定它们的比例与其他对象的比例匹配 `Time``TimeDelta` 对象（如果是UTC时间，则为TAI）：

```>>> t2.tai + TimeDelta(365., format='jd', scale=None)
<Time object: scale='tai' format='iso' value=2011-12-31 23:59:27.068>
```

```>>> t = Time(2450000., 1e-6, format='jd')
>>> t + TimeDelta(0, format='jd') == t
False
```

### 重心和日心光旅行时间修正¶

#### 例子¶

```>>> 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]>
```

```>>> ltt_helio = times.light_travel_time(ip_peg, 'heliocentric')
>>> ltt_helio
<TimeDelta object: scale='tdb' format='jd' value=[-0.00376576 -0.00376712]>
```

```>>> times_heliocentre = times.utc + ltt_helio
```

```>>> time_barycentre = times.tdb + ltt_bary
```

```>>> ltt_bary_jpl = times.light_travel_time(ip_peg, ephemeris='jpl')
>>> ltt_bary_jpl
<TimeDelta object: scale='tdb' format='jd' value=[-0.0037715  -0.00377286]>
>>> (ltt_bary_jpl - ltt_bary).to(u.ms)
<Quantity [-0.00132325, -0.00132861] ms>
```

### 与类时间量的相互作用¶

#### 实例¶

```>>> 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 object: scale='tai' format='gps' value=315576000.0>
>>> Time(10.*u.yr, 1.*u.s, format='gps')
<Time object: scale='tai' format='gps' value=315576001.0>
>>> Time(2000.*u.yr, format='jyear')
<Time object: scale='tt' format='jyear' value=2000.0>
>>> 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 interpretation would be ambiguous. Use float with Besselian year instead.

>>> TimeDelta(10.*u.yr)            # With a quantity, no format is required
<TimeDelta object: scale='None' format='jd' value=3652.5>

>>> 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
<Time object: scale='utc' format='mjd' value=50000.0416667>
>>> 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.]>
```

### 编写自定义格式¶

#### 实例¶

```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
```

```>>> from astropy.time import TimeISO
>>> class TimeYearDayTimeCustom(TimeISO):
...    """
...    Year, day-of-year and time as "<YYYY>-<DOY>T<HH>:<MM>:<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}'))

>>> t = Time('2000-01-01')
>>> t.yday_custom
'2000-001T00:00:00.000'
>>> t2 = Time('2016-001T00:00:00')
>>> t2.iso
'2016-01-01 00:00:00.000'
```

```>>> 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
946684832.0
>>> t.unix_leap - t.unix
32.0
```

### 时区¶

#### 例子¶

`Time` 对象到可识别时区的datetime对象：：

```>>> 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
```

#### 例子¶

```>>> from dateutil.parser import parse
>>> dtime = parse('2020-10-29T08:20:46.950+1100')
>>> Time(dtime)
<Time object: scale='utc' format='datetime' value=2020-10-28 21:20:46.950000>
```

### 自定义字符串格式 `strftime` 和 `strptime`¶

#### 实例¶

```>>> 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'
```

```>>> from astropy.time import Time
>>> t = Time.strptime('23:59:60 30 June 2015', '%H:%M:%S %d %B %Y')
>>> t
<Time object: scale='utc' format='isot' value=2015-06-30T23:59:60.000>
```

## 参考/API¶

### astropy.time 包¶

#### 功能¶

 `update_leap_seconds`([files]) 如果当前的ERFA闰秒表已过期，请尝试更新它。

#### Classes¶

 的配置参数 `astropy.table` . `OperandTypeError`(left, right[, op]) `Time`(val[, val2, format, scale, precision, ...]) 表示和操纵天文学的时间和日期。 从中继承time和TimeDelta的基时间类。 `TimeBesselianEpoch`(val1, val2, scale, ...[, ...]) 贝塞尔纪元年份作为浮点值，如1950.0 `TimeBesselianEpochString`(val1, val2, scale, ...) 贝塞尔纪元年份作为字符串值，如“B1950.0” `TimeCxcSec`(val1, val2, scale, precision, ...) 钱德拉X射线中心秒1998-01-01 00:00:00 TT。 `TimeDatetime`(val1, val2, scale, precision, ...) 将日期表示为Python标准库 `datetime` 对象 `TimeDatetime64`(val1, val2, scale, precision, ...) `TimeDecimalYear`(val1, val2, scale, ...[, ...]) 时间为十进制年，整数值对应于每年第一天的午夜。 `TimeDelta`(val[, val2, format, scale, ...]) 表示两次之间的时差。 `TimeDeltaDatetime`(val1, val2, scale, ...[, ...]) 时间增量日期时间。时间增量 `TimeDeltaFormat`(val1, val2, scale, ...[, ...]) 时间增量表示的基类 `TimeDeltaJD`(val1, val2, scale, precision, ...) 朱利安日的时间增量（86400 SI秒） TimeDelta中缺少单位或格式的警告 `TimeDeltaNumeric`(val1, val2, scale, ...[, ...]) `TimeDeltaSec`(val1, val2, scale, precision, ...) 时间增量（SI秒） `TimeEpochDate`(val1, val2, scale, precision, ...) 支持浮点贝塞尔纪元和朱利安纪元日期的基类 `TimeEpochDateString`(val1, val2, scale, ...) 基类，分别支持字符串Besselian和Julian epoch日期，如“B1950.0”或“J2000.0”。 `TimeFITS`(val1, val2, scale, precision, ...) 适合格式：“ [±Y] 年-月-日 [THH:毫米：SS[.sss] ]". `TimeFormat`(val1, val2, scale, precision, ...) 时间表示的基类。 `TimeFromEpoch`(val1, val2, scale, precision, ...) 基类表示从某个特定纪元开始的间隔为单位时间间隔的浮点倍数的时间（例如。 `TimeGPS`(val1, val2, scale, precision, ...[, ...]) GPS时间：1980-01-06 00:00:00 UTC的秒数，例如630720013.0是2000年1月1日的午夜。 `TimeISO`(val1, val2, scale, precision, ...[, ...]) 符合ISO 8601的日期时间格式“YYYY-MM-DD HH:MM:不锈钢不锈钢...". `TimeISOT`(val1, val2, scale, precision, ...) 符合ISO 8601的日期时间格式“YYYY-MM-DDTHH:毫米:不锈钢不锈钢...". `TimeInfo`([bound]) 用于存储诸如名称、描述、格式等元信息的容器。 `TimeInfoBase`([bound]) 用于存储诸如名称、描述、格式等元信息的容器。 `TimeJD`(val1, val2, scale, precision, ...[, ...]) 朱利安日期时间格式。 `TimeJulianEpoch`(val1, val2, scale, ...[, ...]) 儒略纪元年份作为浮点值，如2000.0 `TimeJulianEpochString`(val1, val2, scale, ...) Julian Epoch year作为字符串值，如“J2000.0” `TimeMJD`(val1, val2, scale, precision, ...[, ...]) 修改了朱利安日期时间格式。 `TimeNumeric`(val1, val2, scale, precision, ...) `TimePlotDate`(val1, val2, scale, precision, ...) Matplotlib `plot_date` 输入：1+从0001-01-01 00:00:00 UTC开始的天数 `TimeString`(val1, val2, scale, precision, ...) 类字符串时间表示的基类。 `TimeUnique`(val1, val2, scale, precision, ...) 时间格式的基类，可以唯一地创建时间对象，而不需要显式格式说明符。 `TimeUnix`(val1, val2, scale, precision, ...) UNIX时间(UTC)：从1970-01-01 00：00：00 UTC开始的秒，忽略闰秒。 `TimeUnixTai`(val1, val2, scale, precision, ...) UNIX时间(TAI)：自1970-01-01 00：00：00 TAI以来经过的SI秒(请参阅警告)。 `TimeYMDHMS`(val1, val2, scale, precision, ...) ymdhms：一种时间格式，表示时间为年、月、日、小时、分钟、秒（因此称为ymdhms）。 `TimeYearDayTime`(val1, val2, scale, ...[, ...]) 年、年、日和时间为“YYYY:多伊：HH:MM:不锈钢不锈钢...". `TimezoneInfo`([utc_offset, dst, tzname]) 的子类 `tzinfo` 对象，在tou datetime方法中用于指定时区。