Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

แปลงอาร์เรย์ datetime เป็นสตริงพร้อมระบุหน่วยใน Python

เพื่อแปลงอาร์เรย์ของวันที่และเวลา (datetime) เป็นอาร์เรย์ของสตริง ให้ใช้เมธอด numpy.datetime_as_string() ใน NumPy เมธอดนี้คืนค่าอาร์เรย์สตริงที่มีรูปร่างเหมือนอินพุต พารามิเตอร์แรกคืออาร์เรย์ timestamp UTC ที่ต้องการจัดรูปแบบ พารามิเตอร์ unit กำหนดหน่วย datetime เพื่อเปลี่ยนความแม่นยำ (ตัวอย่างใช้หน่วยวินาที)

ขั้นตอนการใช้งาน

import numpy as np

สร้างอาร์เรย์ datetime

# 'M' ระบุชนิด datetime, 'm' คือนาที
arr = np.arange('2022-02-20T02:10', 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)

แปลงเป็นสตริงพร้อมหน่วยวินาที

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

โค้ดตัวอย่างสมบูรณ์

import numpy as np

# Create an array of 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)
# Convert to strings with seconds precision
print("\nResult...\n", np.datetime_as_string(arr, unit='s'))

ผลลัพธ์ที่คาดหวัง

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:00' '2022-02-20T03:10:00' '2022-02-20T04:10:00'
 '2022-02-20T05:10:00' '2022-02-20T06:10:00' '2022-02-20T07:10:00']