在Python中將日期時間陣列轉換為帶有UTC時區的字串陣列


要將日期時間陣列轉換為字串陣列,可以使用Python NumPy中的numpy.datetime_as_string()方法。該方法返回一個與輸入陣列形狀相同的字串陣列。第一個引數是要格式化的UTC時間戳陣列。第二個引數是“時區”,即顯示日期時間時要使用的時區資訊。如果為“UTC”,則以Z結尾以指示UTC時間。

步驟

首先,匯入所需的庫:

import numpy as np

建立一個datetime陣列。“M”型別指定datetime:

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)

要將日期時間陣列轉換為字串陣列,可以使用Python NumPy中的numpy.datetime_as_string()方法。該方法返回一個與輸入陣列形狀相同的字串陣列。第一個引數是要格式化的UTC時間戳陣列。第二個引數是“時區”,即顯示日期時間時要使用的時區資訊。如果為‘UTC’,則以Z結尾以指示UTC時間。如果為‘local’,則先轉換為本地時區,然後新增+-####時區偏移量字尾。如果是tzinfo物件,則與‘local’相同,但使用指定的時區:

print("\nResult...\n",np.datetime_as_string(arr, timezone = 'UTC'))

示例

import numpy as np

# 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 = 'UTC'))

輸出

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-20T03:25Z' '2022-02-20T04:25Z' '2022-02-20T05:25Z' '2022-02-20T06:25Z' '2022-02-20T07:25Z' '2022-02-20T08:25Z']

更新於:2022年2月24日

461 次瀏覽

啟動你的職業生涯

透過完成課程獲得認證

開始學習
廣告