Python | Pandas dataframe.at_time()

Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.
Pandasdataframe.at_time() function is used to select all the values in a row corresponding to the input time of the day. If the input time is not present in the dataframe then an empty dataframe is returned.
Syntax: DataFrame.at_time(time, asof=False)
Parameters:
time : datetime.time or string
Returns: values_at_time : type of caller
Note: at_time() function raises exception when the index of the dataframe is not a DatetimeIndex
Example #1: Create a datetime indexed dataframe and retrieve the values at any specific time
Python3
# importing pandas as pdimport pandas as pd# Creating row index values for dataframe# Taken time frequency to be of 12 hours interval# Generating five index value using "period = 5" parameterind = pd.date_range('01/ 01/2000', periods = 5, freq ='12H')# Creating a dataframe with 2 columns# using "ind" as the index for our dataframedf = pd.DataFrame({"A":[1, 2, 3, 4, 5], "B":[10, 20, 30, 40, 50]}, index = ind)# Printing the dataframe# for visualizationdf |
Now find out the values at time “12:00”
Python3
df.at_time('12:00') |
Output :
Example #2: Set the frequency of date_time index for 30 minute duration and query for both valid and invalid time (Not present in the dataframe) .
Python3
# importing pandas as pdimport pandas as pd# Creating row index values for our data frame# We have taken time frequency to be of 30 minutes interval# We are generating eight index value using "period = 8" parameterind = pd.date_range('01/01/2000', periods = 8, freq ='30T')# Creating a dataframe with 2 columns# using "ind" as the index for our dataframedf = pd.DataFrame({"A":[1, 2, 3, 4, 5, 6, 7, 8], "B":[10, 20, 30, 40, 50, 60, 70, 80]}, index = ind)# Printing the dataframedf |
Now let’s query for time “02:00”
Python3
# Find the row values at time "02:00"df.at_time('02:00') |
Output :




