numpy.datetime_as_string#
- numpy.datetime_as_string(arr, unit=None, timezone='naive', casting='same_kind')#
将 datetime 数组转换为字符串数组.
- 参数:
- arrdatetime64 的类数组对象
要格式化的 UTC 时间戳数组.
- unitstr
None,“auto”或 datetime unit 之一.
- timezone{‘naive’, ‘UTC’, ‘local’} 或 tzinfo
显示 datetime 时要使用的时区信息.如果是 ‘UTC’,则以 Z 结尾以指示 UTC 时间.如果是 ‘local’,则首先转换为本地时区,并以 +-#### 时区偏移量为后缀.如果是 tzinfo 对象,则执行与 ‘local’ 相同的操作,但使用指定的时区.
- casting{‘no’, ‘equiv’, ‘safe’, ‘same_kind’, ‘unsafe’}
在 datetime 单位之间更改时允许的强制转换.
- 返回:
- 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 边界的 datetime.传入一个
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'