📜  Python| Pandas PeriodIndex.start_time(1)

📅  最后修改于: 2023-12-03 14:46:22.851000             🧑  作者: Mango

Python | Pandas PeriodIndex.start_time

In Pandas, PeriodIndex represents a sequence of Periods as a time index. We can create a PeriodIndex using various methods which include specifying the frequency of the periods, start date, and end date. Once we have created a PeriodIndex, we can extract various attributes of the periods using different properties provided by the PeriodIndex class. One such property is start_time which returns the start datetime of the given period in the form of a DatetimeIndex.

Syntax
PeriodIndex.start_time
Parameters

None

Return Value

Return the start datetime of the given period in the form of a DatetimeIndex.

Example

Consider the below example where we will create a PeriodIndex with day frequency for the year 2021. We will assign this index to a dataframe containing random numbers. We will then extract the start_time attribute for each period in the PeriodIndex.

import pandas as pd
import numpy as np

periods = pd.period_range('2021', freq='D', periods=365)
df = pd.DataFrame(np.random.rand(len(periods),1), index = periods, columns=['Random Number'])
start_times = periods.start_time

print(df)
print("Start times: ")
print(start_times)

Output:

            Random Number
2021-01-01       0.946136
2021-01-02       0.157952
2021-01-03       0.226132
2021-01-04       0.052401
2021-01-05       0.216595
...                   ...
2021-12-27       0.514985
2021-12-28       0.859695
2021-12-29       0.600322
2021-12-30       0.750302
2021-12-31       0.690358

[365 rows x 1 columns]
Start times: 
DatetimeIndex(['2021-01-01', '2021-01-02', '2021-01-03', '2021-01-04',
               '2021-01-05', '2021-01-06', '2021-01-07', '2021-01-08',
               '2021-01-09', '2021-01-10',
               ...
               '2021-12-22', '2021-12-23', '2021-12-24', '2021-12-25',
               '2021-12-26', '2021-12-27', '2021-12-28', '2021-12-29',
               '2021-12-30', '2021-12-31'],
              dtype='datetime64[ns]', length=365, freq='D')

As we can see, we have created a PeriodIndex with day frequency for the year 2021. We have assigned this index to a dataframe containing random numbers. We have then extracted the start_time attribute for each period in the PeriodIndex and printed the same. We can observe that the start_time attribute returns the start datetime of each period in the PeriodIndex in the form of a DatetimeIndex.