Python
 Computer >> コンピューター >  >> プログラミング >> Python

日時の配列をPythonで分日時単位を渡す文字列の配列に変換します


日時の配列を文字列の配列に変換するには、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']

  1. Python DateTime文字列を整数ミリ秒に変換する方法は?

    Pythonでは、timeモジュールを使用して現在の時刻をミリ秒単位で取得できます。 time.time関数(浮動小数点値として)を使用して、時間を秒単位で取得できます。ミリ秒に変換するには、1000を掛けて四捨五入する必要があります。 例 import time milliseconds = int(round(time.time() * 1000)) print(milliseconds) 出力 これにより、出力が得られます- 1514825676008 datetimeオブジェクトをミリ秒のタイムスタンプに変換する場合は、timestamp関数を使用してから、上記と同じ計算を適用して

  2. Pythonで日付を日時に変換する方法は?

    datetimeモジュールのcombineメソッドを使用して、日付と時刻を組み合わせて、datetimeオブジェクトを作成できます。時間オブジェクトではなく日付オブジェクトがある場合は、datetimeオブジェクトを使用して時間オブジェクトを最小に初期化できます(最小時間は深夜を意味します)。 例 from datetime import date from datetime import datetime my_date = date.today() my_time = datetime.min.time() my_datetime = datetime.combine(my_date, m