numpy.datetime_as_string#
- numpy.datetime_as_string(arr, unit=None, timezone='naive', casting='same_kind')#
将日期时间数组转换为字符串数组。
- 参数:
- arrdatetime64 类型的类数组对象
要格式化的 UTC 时间戳数组。
- unit字符串
取值可为 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'