numpy.datetime_as_string#
- numpy.datetime_as_string(arr, unit=None, timezone='naive', casting='same_kind')#
将日期时间数组转换为字符串数组.
- 参数:
- arr类数组的 datetime64
要格式化的UTC时间戳数组.
- unitstr
None、’auto’ 或一个 datetime 单位 之一.
- 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')
请注意,我们选择了跨越夏令时边界的日期时间.传入一个
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'