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

PythonPandas-指定された期間の週を取得します


特定の期間の週を取得するには、 period.weekofyearを使用します 財産。まず、必要なライブラリをインポートします-

import pandas as pd

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

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

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

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

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

res1 = period1.weekofyear
res2 = period2.weekofyear

以下はコードです

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 = 4, day = 16, hour = 2, minute = 35)

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

# get the week of the year from two Period objects
res1 = period1.weekofyear
res2 = period2.weekofyear

# Return the week of the year from the two Period objects
print("\nWeek of the year from the 1st Period object ...\n", res1)
print("\nWeek of the year from the 2nd Period object...\n", res2)

出力

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

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

Week of the year from the 1st Period object ...
39

Week of the year from the 2nd Period object...
15

  1. PythonPandas-指定されたタイムスタンプを期間に変換する

    指定されたタイムスタンプを期間に変換するには、タイムスタンプ.to_period()を使用します 方法。その中で、 freqを使用して頻度を設定します パラメータ。 まず、必要なライブラリをインポートします- import pandas as pd パンダでタイムスタンプオブジェクトを設定します timestamp = pd.Timestamp('2021-09-14T15:12:34.261811624') 次に、タイムスタンプを期間に変換します。値が「M」の「freq」パラメータを使用して、頻度を月に設定しました timestamp.to_period(freq=&#

  2. Pythonを使用して今週を取得するにはどうすればよいですか?

    YOUは、datetimeモジュールのisocalender関数を使用して、現在の週を取得できます。最初に日付のオブジェクトを作成してから、このオブジェクトに対してisocalender()を呼び出します。これにより、3タプルの年、週番号、および曜日が返されます。 例 import datetime my_date = datetime.date.today() # if date is 01/01/2018 year, week_num, day_of_week = my_date.isocalendar() print("Week #" + str(week_num)