VOOZH about

URL: https://www.geeksforgeeks.org/pandas/get-the-hour-from-timestamp-in-pandas/

⇱ Get the Hour from timestamp in Pandas - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Get the Hour from timestamp in Pandas

Last Updated : 15 Jul, 2025

Let's learn how to get the hour from the timestamp in Pandas DataFrame.

Extract Hour from Timestamps in Pandas DataFrame

Pandas offers convenient tools to extract specific time components from timestamps in your data, such as the hour, which is useful for time-based analysis.

  1. Convert the timestamp to datetime: First, ensure the column is in datetime format using pd.to_datetime(). If the column is not already in this format, this step converts it to a proper datetime object that can be used for time-based operations.
  2. Extract the hour: After converting to datetime, use the .dt.hour accessor to extract the hour component of the timestamp. This returns the hour in 24-hour format as an integer.

Output
 timestamp hour
0 2024-11-29 08:45:32 8
1 2024-11-29 13:20:45 13
2 2024-11-29 18:10:10 18

You can also extract minutes, seconds and day of the week using:

  • Get the Minute: df['timestamp'].dt.minute
  • Get the Second: df['timestamp'].dt.second
  • Get the Day of the Week: df['timestamp'].dt.dayofweek

Extract Hour from Current Timestamp

To begin with, let's look at how to extract the hour from the current timestamp.


Output
Current Timestamp: 2024-11-29 11:13:42.385191
Hour: 11

Here, we use pd.Timestamp.now() to get the current timestamp and then access the hour attribute to retrieve the hour.

Extract Hour from a Specific Timestamp

You can also create a timestamp with a specific date and time and extract the hour.


Output
Timestamp: 2020-07-21 06:30:44+05:30
Hour: 6

In this example, the timestamp is created with specific details, including the timezone. The hour attribute extracts the hour part from the timestamp.

Handling Timestamps in CSV Files

Often, timestamp data is read from CSV files. Here’s how to extract the hour from such data.

Dataset Link:xyz.csv

Output

πŸ‘ Handling-Timestamps-in-CSV-Files

This demonstrates how to read timestamp data from a CSV file, convert it to datetime format, and extract the hour from each timestamp.

Comment

Explore