使用 Python 和 pytz 时区对象将日期时间数组转换为字符串数组
要将日期时间数组转换为字符串数组,请在 Python NumPy 中使用 numpy.datetime_as_string() 方法。该方法返回一个与输入数组形状相同的字符串数组。第一个参数是要格式化的 UTC 时间戳数组。
第二个参数是“时区”,即显示日期时间时要使用的时区信息。如果为“UTC”,则以 Z 结尾以指示 UTC 时间。如果为“local”,则先转换为本地时区,然后以 +-#### 时区偏移量结尾。如果为 tzinfo 对象,则与“local”相同,但使用指定的时区。
步骤
首先,导入所需的库。对于 pytz 时区,我们导入了 'pytz' 库 -
import numpy as np import pytz
创建日期时间数组。'M' 类型指定日期时间 -
arr = np.arange('2022-02-20T03:25', 6*60, 60, dtype='M8[m]')显示我们的数组 -
print("Array...\n",arr)获取数据类型 -
print("\nArray datatype...\n",arr.dtype)
获取数组的维度 -
print("\nArray Dimensions...\n",arr.ndim)获取数组的形状 -
print("\nOur Array Shape...\n",arr.shape)获取数组的元素数量 -
print("\nNumber of elements in the Array...\n",arr.size)要将日期时间数组转换为字符串数组,请使用 numpy.datetime_as_string() 方法。该方法返回一个与输入数组形状相同的字符串数组 -
print("\nResult...\n",np.datetime_as_string(arr, timezone=pytz.timezone('US/Eastern')))
示例
import numpy as np
import pytz
# Create an array of datetime
# The 'M' type specifies datetime
arr = np.arange('2022-02-20T03:25', 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, timezone=pytz.timezone('US/Eastern')))输出
Array... ['2022-02-20T03:25' '2022-02-20T04:25' '2022-02-20T05:25' '2022-02-20T06:25' '2022-02-20T07:25' '2022-02-20T08:25'] Array datatype... datetime64[m] Array Dimensions... 1 Our Array Shape... (6,) Number of elements in the Array... 6 Result... ['2022-02-19T22:25-0500' '2022-02-19T23:25-0500' '2022-02-20T00:25-0500' '2022-02-20T01:25-0500' '2022-02-20T02:25-0500' '2022-02-20T03:25-0500']
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP