numpy.
datetime_as_string
将日期时间数组转换为字符串数组。
要格式化的UTC时间戳数组。
无“自动”或 datetime unit .
显示日期时间时要使用的时区信息。如果是“UTC”,则以Z结尾,表示UTC时间。如果是“本地”,请先转换为本地时区,并在其后面加上一个+-时区偏移量。如果是Tzinfo对象,则与“local”相同,但使用指定的时区。
在日期时间单位之间切换时允许的强制转换。
与形状相同的字符串数组 arr .
实例
>>> 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 时区对象将打印适当的偏移量
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'