Home > Mobile >  How to get 15 minutes time intervals for given duration pandas data frame
How to get 15 minutes time intervals for given duration pandas data frame

Time:07-26

I have an input data frame df

start_time end_time
  10:15     11:30
  14:30     15:15
  02:00     03:15

Expect output

Time_Intervals
[10:15, 10:30, 10:45, 11:00, 11:15, 11:30]
[14:30, 14:45, 15:00, 15:15]
[02:00, 02:15, 02:30, 02:45, 03:00, 03:15]

Can anyone please help me with this?

CodePudding user response:

You can use date_range

pandas.date_range("10:15", "11:30", freq="15min")

You can use apply and and write a custom preprocessing function like this.

def time_intervals(start, end):
    # credits DerrylG
    return return pd.date_range(
        start, end, freq="15min"
    ).strftime("%H:%M").tolist()

df["time_intervals"] = df.apply(
    lambda x: time_intervals(x.start_time, x.end_time), axis=1
)

CodePudding user response:

You can use pandas.apply with axis=1 for gettig value from 'start_time' and 'end_time', pd.date_range and strftime('%H:%M') for getting like Hour:Min. By thanks DarrylG you can try like below.

df['Time_Intervals'] = df.apply(
    lambda row : pd.date_range(
        row['start_time'], row['end_time'], freq='15T'
    ).strftime("%H:%M").tolist(), axis=1)

print(df)

  start_time end_time                              Time_Intervals
0      10:15    11:30  [10:15, 10:30, 10:45, 11:00, 11:15, 11:30]
1      14:30    15:15                [14:30, 14:45, 15:00, 15:15]
2       2:00     3:15  [02:00, 02:15, 02:30, 02:45, 03:00, 03:15]

Explanation, How convert DatetimeIndex to desired format?

# Explanation
lst = pd.date_range('14:30', '15:15', freq='15T').strftime("%H:%M").tolist()
print(lst)
# ['14:30', '14:45', '15:00', '15:15']
  • Related