Pandas DataFrame at_time() Method

Rate this post

Preparation

Before any data manipulation can occur, two (2) new libraries will require installation.

  • The Pandas library enables access to/from a DataFrame.
  • The NumPy library supports multi-dimensional arrays and matrices in addition to a collection of mathematical functions.

To install these libraries, navigate to an IDE terminal. At the command prompt ($), execute the code below. For the terminal used in this example, the command prompt is a dollar sign ($). Your terminal prompt may be different.

$ pip install pandas

Hit the <Enter> key on the keyboard to start the installation process.

$ pip install numpy

Hit the <Enter> key on the keyboard to start the installation process.

If the installations were successful, a message displays in the terminal indicating the same.


Feel free to view the PyCharm installation guide for the required libraries.


Add the following code to the top of each code snippet. This snippet will allow the code in this article to run error-free.

import pandas as pd
import numpy as np 

DataFrame at_time()

The at_time() method selects and retrieves values at a specified time each day. An error occurs if the index is not a DateTimeIndex. To fully understand this method, feel free to watch this short tutorial:

The syntax for this method is as follows:

DataFrame.at_time(time, asof=False, axis=None)
ParameterDescription
timeThis parameter must be a valid datetime.time or string.
asofIf set to True, this parameter uses the start date/time. By default, False.
axisIf zero (0) or index is selected, apply to each column. Default 0.
If one (1) apply to each row.

For this example, the stock prices for Apple return three (3) times per day at eight (8) hour intervals.

todays_date  = date.today()
stock_drange  = pd.date_range(todays_date, periods=3, freq='8H')
stock_df = pd.DataFrame({'AAPL': [10.34, 9.83, 10.39]}, index=stock_drange)
print(stock_df)

result = stock_df.at_time('08:00')
print(result)
  • Line [1] uses today() to retrieve the current date/time and saves it to todays_date.
  • Line [2] uses date_range() to set the date, period(s), frequencies and saves them to stock_drange.
  • Line [3] creates a DataFrame. Sets the index to stock_drange and saves it to stock_df.
  • Line [4] outputs the result to the terminal.
  • Line [5] retrieves the stock price details for the specified time (’08:00’) and saves it to result.
  • Line [6] outputs the result to the terminal.

Output

AAPL
2022-01-06 00:00:00 10.34
2022-01-06 08:00:00  9.83
2022-01-06 16:00:00 10.39
AAPL
2022-01-06 08:00:00  9.83

More Pandas DataFrame Methods

Feel free to learn more about the previous and next pandas DataFrame methods (alphabetically) here:

Also, check out the full cheat sheet overview of all Pandas DataFrame methods.