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

Python Pandas – BusinessHourオフセットに適用された増分の数を取得する方法

はじめに

PandasのBusinessHourオフセットに適用された増分の数を確認するには、BusinessHour.nプロパティを使用します。本記事では、具体的なコード例と実行結果をもとに、その基本的な使い方をわかりやすく解説します。

必要なライブラリのインポート

まず、Pandasをインポートします。

import pandas as pd

タイムスタンプの設定

Pandasでタイムスタンプオブジェクトを設定します。

timestamp = pd.Timestamp('2021-1-1 01:55:30')

BusinessHourオフセットの作成

続いて、BusinessHourオフセットを作成します。startにはカスタム営業時間の開始時刻を、endには終了時刻を24時間形式で指定します。さらに、引数nには適用する増分の数を設定します。

bhOffset = pd.tseries.offsets.BusinessHour(start="09:30", end="18:00", n=8)

更新後のタイムスタンプを表示します。

print("\nUpdated Timestamp...\n", timestamp + bhOffset)

そして、BusinessHourオブジェクトに適用された増分の数を返します。

print("\nThe count of increments on the BusinessHour object..\n", bhOffset.n)

完全なコード例

以下に、ここまでの手順をまとめた完全なコードを示します。

import pandas as pd

# タイムスタンプオブジェクトを設定
timestamp = pd.Timestamp('2021-1-1 01:55:30')

# タイムスタンプを表示
print("Timestamp...\n", timestamp)

# BusinessHourオフセットを作成
# BusinessHourはDateOffsetのサブクラスです
# 「start」は営業開始時刻(24時間形式)
# 「end」は営業終了時刻(24時間形式)
bhOffset = pd.tseries.offsets.BusinessHour(start="09:30", end="18:00", n=8)

# BusinessHourオフセットを表示
print("\nBusinessHour Offset...\n", bhOffset)

# 更新後のタイムスタンプを表示
print("\nUpdated Timestamp...\n", timestamp + bhOffset)

# BusinessHourオブジェクトに適用された増分の数を返す
print("\nThe count of increments on the BusinessHour object..\n", bhOffset.n)

実行結果

上記のコードを実行すると、以下のような出力が得られます。

Timestamp...
 2021-01-01 01:55:30

BusinessHour Offset...
 <8 * BusinessHours: BH=09:30-18:00>

Updated Timestamp...
 2021-01-01 17:30:00

The count of increments on the BusinessHour object..
 8

まとめ

BusinessHour.nプロパティを使えば、BusinessHourオフセットに適用された増分の数を簡単に取得できます。上記の例では、n=8として作成したオフセットに対して「8」が返されていることが確認できます。営業時間を考慮した日時計算が必要な業務システムやデータ分析の場面で、ぜひ活用してみてください。

  1. Python・Pandas入門:オフセットオブジェクトに適用された頻度の名前を取得する方法

    Pandasでオフセット(DateOffset)オブジェクトに適用されている頻度の名前を取得するには、offset.name プロパティを使用します。この記事では、具体的なコード例とともにその使い方を解説します。必要なライブラリのインポートまず、必要なライブラリをインポートします。from pandas.tseries.frequencies import to_offset import pandas as pdタイムスタンプの作成Pandasでタイムスタンプオブジェクトを設定します。timestamp = pd.Timestamp(2021-09-26 03:25:02.000045)Da

  2. Python Pandas – 指定したDateOffsetオブジェクトに適用された頻度を返す方法

    Pandasで指定されたDateOffsetオブジェクトに適用されている頻度を取得するには、offset.freqstr属性を使用します。この属性は、DateOffsetオブジェクトに設定された頻度を「5D」のような文字列形式で返してくれます。また、to_offset()関数を使うことで、頻度を表す文字列からDateOffsetオブジェクトを簡単に生成できます。 まず、必要なライブラリをインポートしましょう。 from pandas.tseries.frequencies import to_offset import pandas as pd 次に、Pandasでタイムスタンプオブジェクトを