Computer >> Máy Tính >  >> Lập trình >> Python

Chuyển đổi một mảng ngày giờ thành một mảng chuỗi chuyển đơn vị ngày giờ giờ bằng Python

Để chuyển đổi một mảng ngày giờ thành một mảng chuỗi, hãy sử dụng phương thức numpy.datetime_as_string () trong Python Numpy. Phương thức trả về một mảng chuỗi có cùng hình dạng với mảng đầu vào. Tham số đầu tiên là mảng dấu thời gian UTC để định dạng. Tham số "đơn vị" đặt đơn vị ngày giờ để thay đổi độ chính xác. Chúng tôi đã vượt qua đơn vị giờ

Các bước

Đầu tiên, hãy nhập thư viện được yêu cầu -

import numpy as np

Tạo một mảng ngày giờ. Loại 'M' chỉ định ngày giờ -

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

Hiển thị mảng của chúng tôi -

print("Array...\n",arr)

Nhận loại dữ liệu:-

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

Nhận các kích thước của Mảng -

print("\nArray Dimensions...\n",arr.ndim)

Nhận hình dạng của Mảng -

print("\nOur Array Shape...\n",arr.shape)

Nhận số phần tử của Mảng -

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

Để chuyển đổi một mảng ngày giờ thành một mảng chuỗi, hãy sử dụng phương thức numpy.datetime_as_string () trong Python Numpy -

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

Ví dụ

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
# The first parameter is the array of UTC timestamps to format
# The "units" parameter sets the datetime unit to change the precision
# We have passed the hours unit
print("\nResult...\n",np.datetime_as_string(arr, unit ='h'))

Đầu ra

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