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

PythonPandas-Periodオブジェクトから年の日を取得します


Periodオブジェクトから年の日を取得するには、 period.dayofyearを使用します プロパティ。

まず、必要なライブラリをインポートします-

import pandas as pd

pandas.Periodは期間を表します。 2つのPeriodオブジェクトの作成-

period1 = pd.Period("2020-09-23")
period2 = pd.Period(freq="D", year = 2021, month = 7, day = 16, hour = 2, minute = 35)

期間オブジェクトを表示する-

print("Period1...\n", period1)
print("Period2...\n", period2)

2つのPeriodオブジェクトから年の日を取得します-

res1 = period1.dayofyear
res2 = period2.dayofyear

以下はコードです-

import pandas as pd

# The pandas.Period represents a period of time
# creating two Period objects
period1 = pd.Period("2020-09-23")
period2 = pd.Period(freq="D", year = 2021, month = 7, day = 16, hour = 2, minute = 35)

# display the Period objects
print("Period1...\n", period1)
print("Period2...\n", period2)

# get the day of the year from two Period objects
res1 = period1.dayofyear
res2 = period2.dayofyear

# Return the day of the year from the two Period objects
# The return value ranges between 1 to 365 for regular years and 1 to 366 for leap years
print("\nDay of the year from the 1st Period object ...\n", res1)
print("\nDay of the year from the 2nd Period object...\n", res2)

出力

これにより、次のコードが生成されます-

Period1...
2020-09-23
Period2...
2021-07-16

Day of the year from the 1st Period object ...
267

Day of the year from the 2nd Period object...
197

  1. Python-PandasのTimestampオブジェクトから平日を取得します

    Timestampオブジェクトから平日を取得するには、 timestamp.weekday()を使用します 方法。まず、必要なライブラリをインポートします- import pandas as pd import datetime パンダでタイムスタンプを設定します。タイムスタンプオブジェクトを作成する timestamp = pd.Timestamp(datetime.datetime(2021, 5, 12)) その年の平日を取得します。平日は、月曜日==0、火曜日==1…日曜日==6の数字で表されます。 timestamp.weekday() 例 以下はコードです import

  2. Pythonの年間最優秀日

    「YYYY-MM-DD」の形式の日付があるとします。その年の日数を返す必要があります。したがって、日付が「2019-02-10」の場合、これは1年の41日目です。 これを解決するには、次の手順に従います- Dが[0、31、28、31、30、31、30、31、31、30、31、30、31]のような日数の配列であるとします 日付を年、月、日のリストに変換します 年がうるう年の場合は、日付D [2]=29を設定します 月mm–1までの日数とそれ以降の日数を合計します。 例 理解を深めるために、次の実装を見てみましょう- class Solution(object):   &nbs