How to Extract Hour from Datetime in pandas Easily
To extract the hour from a datetime column in pandas, use the
.dt.hour accessor on a datetime Series. This returns the hour as an integer from 0 to 23 for each datetime value.Syntax
Use the .dt.hour attribute on a pandas Series with datetime values to get the hour part.
Series.dt: Accessor for datetime properties.hour: Extracts the hour (0-23) from each datetime.
python
df['hour'] = df['datetime_column'].dt.hour
Example
This example shows how to create a pandas DataFrame with datetime values and extract the hour from the datetime column.
python
import pandas as pd data = {'datetime_column': ['2024-06-01 08:45:00', '2024-06-01 15:30:00', '2024-06-01 23:59:59']} df = pd.DataFrame(data) df['datetime_column'] = pd.to_datetime(df['datetime_column']) df['hour'] = df['datetime_column'].dt.hour print(df)
Output
datetime_column hour
0 2024-06-01 08:45:00 8
1 2024-06-01 15:30:00 15
2 2024-06-01 23:59:59 23
Common Pitfalls
Common mistakes include trying to extract the hour from a column that is not in datetime format, which causes errors or incorrect results. Always convert the column to datetime using pd.to_datetime() before extracting the hour.
Another mistake is using string methods instead of datetime accessors, which is less efficient and error-prone.
python
import pandas as pd data = {'datetime_column': ['2024-06-01 08:45:00', '2024-06-01 15:30:00']} df = pd.DataFrame(data) # Wrong: trying to extract hour without datetime conversion # This will raise an error # df['hour'] = df['datetime_column'].dt.hour # Right: convert to datetime first df['datetime_column'] = pd.to_datetime(df['datetime_column']) df['hour'] = df['datetime_column'].dt.hour print(df)
Output
datetime_column hour
0 2024-06-01 08:45:00 8
1 2024-06-01 15:30:00 15
Quick Reference
| Operation | Code Example | Description |
|---|---|---|
| Convert to datetime | df['col'] = pd.to_datetime(df['col']) | Ensure column is datetime type |
| Extract hour | df['hour'] = df['col'].dt.hour | Get hour (0-23) from datetime |
| Check dtype | df['col'].dtype | Verify column type is datetime64[ns] |
Key Takeaways
Always convert your column to datetime type before extracting the hour using pd.to_datetime().
Use the .dt.hour accessor on a datetime Series to get the hour as an integer from 0 to 23.
Avoid using string methods to extract time parts; datetime accessors are more reliable and faster.
Check your column's data type with .dtype to ensure it is datetime before extraction.
Extracting the hour is useful for time-based analysis like grouping or filtering by hour.