在 Python 中,使用 numpy.datetime_as_string() 方法将日期和时间数组转换为字符串数组


若要将日期和时间数组转换为字符串数组,请在 Python Numpy 中使用 numpy.datetime_as_string() 方法,该方法将返回与输入数组形状相同的字符串数组。第一个参数是要格式化的 UTC 时间戳数组。“units”参数设置日期和时间单位,以改变精度。

步骤

首先,导入所需的库 −

import numpy as np

创建日期和时间的数组。'M' 类型指定了日期和时间 −

arr = np.arange('2022-02-20T02:10', 6*60, 60, dtype='M8[m]')

若要将日期和时间数组转换为字符串数组,请使用 Python Numpy 中的 numpy.datetime_as_string() 方法 −

print("\nResult...\n",np.datetime_as_string(arr, unit ='m'))

示例

import numpy as np

# Create an array of datetime
# The 'M' type specifies datetime
arr = np.arange('2022-02-20T02:10', 6*60, 60, dtype='M8[m]')

# Displaying our array
print("Array...\n",arr)

# Get the datatype
print("\nArray datatype...\n",arr.dtype)

# Get the dimensions of the Array
print("\nArray Dimensions...\n",arr.ndim)

# Get the shape of the Array
print("\nOur Array Shape...\n",arr.shape)

# Get the number of elements of the Array
print("\nNumber of elements in the Array...\n",arr.size)

# To convert an array of datetimes into an array of strings, use the numpy.datetime_as_string() method in Python Numpy
# The method returns an array of strings the same shape as the input array

print("\nResult...\n",np.datetime_as_string(arr, unit ='m'))

输出

Array...
['2022-02-20T02:10' '2022-02-20T03:10' '2022-02-20T04:10'
'2022-02-20T05:10' '2022-02-20T06:10' '2022-02-20T07:10']

Array datatype...
datetime64[m]

Array Dimensions...
1

Our Array Shape...
(6,)

Number of elements in the Array...
6

Result...
['2022-02-20T02:10' '2022-02-20T03:10' '2022-02-20T04:10'
'2022-02-20T05:10' '2022-02-20T06:10' '2022-02-20T07:10']

更新时间: 2022-2-28

2000+ 视图

开启您的 职业

通过完成课程获得认证

开始
广告
© . All rights reserved.