numpy.datetime_as_string#

numpy.datetime_as_string(arr, unit=None, timezone='naive', casting='same_kind')#

將日期時間陣列轉換為字串陣列。

參數:
arrdatetime64 的類陣列

要格式化的 UTC 時間戳記陣列。

unitstr

None、‘auto’ 或 日期時間單位 之一。

timezone{‘naive’, ‘UTC’, ‘local’} 或 tzinfo

顯示日期時間時使用的時區資訊。 如果是 ‘UTC’,則以 Z 結尾表示 UTC 時間。 如果是 ‘local’,則先轉換為本地時區,並加上 +-#### 時區偏移量後綴。 如果是 tzinfo 物件,則與 ‘local’ 相同,但使用指定的時區。

casting{‘no’, ‘equiv’, ‘safe’, ‘same_kind’, ‘unsafe’}

在日期時間單位之間變更時允許的轉型。

傳回值:
str_arrndarray

arr 相同形狀的字串陣列。

範例

>>> import numpy as np
>>> import pytz
>>> d = np.arange('2002-10-27T04:30', 4*60, 60, dtype='M8[m]')
>>> d
array(['2002-10-27T04:30', '2002-10-27T05:30', '2002-10-27T06:30',
       '2002-10-27T07:30'], dtype='datetime64[m]')

將時區設定為 UTC 會顯示相同的資訊,但帶有 Z 後綴

>>> np.datetime_as_string(d, timezone='UTC')
array(['2002-10-27T04:30Z', '2002-10-27T05:30Z', '2002-10-27T06:30Z',
       '2002-10-27T07:30Z'], dtype='<U35')

請注意,我們選取的日期時間跨越了 DST 邊界。 傳入 pytz 時區物件將會印出適當的偏移量

>>> np.datetime_as_string(d, timezone=pytz.timezone('US/Eastern'))
array(['2002-10-27T00:30-0400', '2002-10-27T01:30-0400',
       '2002-10-27T01:30-0500', '2002-10-27T02:30-0500'], dtype='<U39')

傳入單位將會變更精確度

>>> np.datetime_as_string(d, unit='h')
array(['2002-10-27T04', '2002-10-27T05', '2002-10-27T06', '2002-10-27T07'],
      dtype='<U32')
>>> np.datetime_as_string(d, unit='s')
array(['2002-10-27T04:30:00', '2002-10-27T05:30:00', '2002-10-27T06:30:00',
       '2002-10-27T07:30:00'], dtype='<U38')

‘casting’ 可用於指定是否可以變更精確度

>>> np.datetime_as_string(d, unit='h', casting='safe')
Traceback (most recent call last):
    ...
TypeError: Cannot create a datetime string as units 'h' from a NumPy
datetime with units 'm' according to the rule 'safe'