I want to create pandas.Period
for a custom time period, for example for a duration starting_time = pd.Timestamp('2024-01-01 09:15:00')
and ending_time = pd.Timestamp('2024-01-05 08:17:00')
.
One way to achieving this is by first getting the pandas.Timedelta
and then create pandas.Period
.
import pandas as pd
# Define start and end times
starting_time = pd.Timestamp('2024-01-01 09:15:00')
ending_time = pd.Timestamp('2024-01-05 08:17:00')
# Calculate the duration (period) between the two timestamps
period_duration = ending_time - starting_time
period_duration_in_minutes = (period_duration.total_seconds()) //60
freq_str = f"{period_duration_in_minutes}min"
period = pd.Period(starting_time, freq = freq_str)
print(period.start_time)
print(period.end_time)
But I need a straightforward approach, something like this (I know this won’t work)-
period = pd.Period(start_time = starting_time, end_time=ending_time)
You don't need to compute the duration in minutes, just pass the subtraction:
pd.Period(starting_time, freq=ending_time-starting_time)
Which is almost your ideal straightforward approach.
Output:
Period('2024-01-01 09:15', '5702min')
Note that you could also use a function to have the desired parameters:
def cust_period(start, end):
return pd.Period(value=start, freq=end-start)
cust_period(starting_time, ending_time)
# Period('2024-01-01 09:15', '5702min')