Pandas dataframe.between_time()
Last Updated :
29 Nov, 2024
Improve
In Pandas, between_time() function is used to filter data in a DataFrame based on specific times of the day, regardless of the actual date.
Syntax: DataFrame.between_time(start_time, end_time, include_start=True, include_end=True)
Parameters:
- start_time (str or datetime): The start time for filtering in HH:MM:SS format.
- end_time (str or datetime): The end time for filtering in HH:MM:SS format.
- include_start (bool, default True): Whether to include the start_time in the output.
- include_end (bool, default True): Whether to include the end_time in the output.
The function returns a DataFrame containing rows with times between start_time and end_time.
This function is particularly useful when working with time-series data where the index is a DatetimeIndex, and you need to extract entries between two given times.
Example of Using between_time() to Filter Data by Time
- The DataFrame is indexed with timestamps.
- The between_time() function filters the rows with times between 09:00:00 and 12:00:00, including both the start_time and end_time by default.
- The resulting DataFrame only contains rows that fall within the specified time range, making it easy to focus on specific periods of the day.
import pandas as pd
# Sample DataFrame with DatetimeIndex
data = {
'value': [10, 20, 30, 40, 50, 60]
}
index = pd.to_datetime(['2024-11-28 08:00:00', '2024-11-28 09:00:00', '2024-11-28 10:00:00',
'2024-11-28 11:00:00', '2024-11-28 12:00:00', '2024-11-28 13:00:00'])
df = pd.DataFrame(data, index=index)
print("Original DataFrame:")
display(df)
# Using between_time to filter between 09:00:00 and 12:00:00
filtered_df = df.between_time('09:00:00', '12:00:00')
print("\nDataFrame after filtering between 09:00:00 and 12:00:00:")
display(filtered_df)
Output:
The pandas between_time() function is an essential tool for filtering data based on specific time ranges, especially when working with time-series data in Python.