numpy.datetime_as_string#
- numpy.datetime_as_string(arr, unit=None, timezone='naive', casting='same_kind')#
将日期时间数组转换为字符串数组。
- 参数:
- arr类数组对象,包含 datetime64
要格式化的 UTC 时间戳数组。
- unit字符串
None、‘auto’ 或 datetime 单位 之一。
- timezone{‘naive’, ‘UTC’, ‘local’} 或 tzinfo
显示日期时间时要使用的时区信息。如果为 ‘UTC’,则以 Z 结尾以指示 UTC 时间。如果为 ‘local’,则先转换为本地时区,并加上 +-#### 时区偏移量。如果为 tzinfo 对象,则与 ‘local’ 相同,但使用指定的时区。
- casting{‘no’, ‘equiv’, ‘safe’, ‘same_kind’, ‘unsafe’}
更改 datetime 单位时允许的转换。
- 返回:
- str_arrndarray
一个字符串数组,形状与 arr 相同。
示例
>>> import numpy as np >>> from zoneinfo import ZoneInfo >>> 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 界限的日期时间。传入
ZoneInfo对象将打印相应的偏移量>>> np.datetime_as_string(d, timezone=ZoneInfo('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'