Python Pandas: How to Extract Hours, Minutes, and Seconds from Datetime in Pandas
Isolating time components from datetime columns is a common operation in data analysis. Whether you are grouping sales data by hour of the day, filtering log entries to business hours, or creating time-based features for a machine learning model, you need to extract individual time components from full datetime values. Pandas provides the .dt accessor for this purpose, offering fast vectorized access to hours, minutes, seconds, and other components without writing loops.
In this guide, you will learn how to extract time components from datetime columns, calculate total seconds, and apply these techniques to practical scenarios like hourly aggregation and time-based filtering.
Extracting Time Components with the .dt Accessor
The .dt accessor provides direct access to individual datetime components on an entire column at once. First, ensure your column is a proper datetime64 type, then access the components you need:
import pandas as pd
df = pd.DataFrame({
'timestamp': ['2024-01-15 12:30:45', '2024-01-15 14:15:00', '2024-01-15 09:45:30']
})
# Convert strings to datetime
df['timestamp'] = pd.to_datetime(df['timestamp'])
# Extract individual components
df['hour'] = df['timestamp'].dt.hour
df['minute'] = df['timestamp'].dt.minute
df['second'] = df['timestamp'].dt.second
print(df)
Output:
timestamp hour minute second
0 2024-01-15 12:30:45 12 30 45
1 2024-01-15 14:15:00 14 15 0
2 2024-01-15 09:45:30 9 45 30
Each .dt attribute returns a Series of integers, making the results ready for arithmetic, grouping, or filtering.
Working with Time-Only Strings
When your data contains time values without dates, pd.to_datetime() still parses them correctly. Pandas assigns a default date, but the time components are extracted the same way:
import pandas as pd
df = pd.DataFrame({
'time': ['12:30:45', '14:15:00', '09:45:30']
})
df['time'] = pd.to_datetime(df['time'])
df['hour'] = df['time'].dt.hour
df['minute'] = df['time'].dt.minute
df['second'] = df['time'].dt.second
print(df[['hour', 'minute', 'second']])
Output:
hour minute second
0 12 30 45
1 14 15 0
2 9 45 30
Calculating Total Seconds Since Midnight
Converting a time to a single numeric value is useful for plotting, distance calculations, or creating features for analysis:
import pandas as pd
df = pd.DataFrame({
'timestamp': pd.to_datetime(['12:30:45', '14:15:00', '00:05:30'])
})
df['total_seconds'] = (
df['timestamp'].dt.hour * 3600 +
df['timestamp'].dt.minute * 60 +
df['timestamp'].dt.second
)
print(df[['timestamp', 'total_seconds']])
Output:
timestamp total_seconds
0 2026-02-17 12:30:45 45045
1 2026-02-17 14:15:00 51300
2 2026-02-17 00:05:30 330
12:30:45 translates to 45,045 seconds after midnight (12 times 3600 + 30 times 60 + 45).
Using total_seconds() with Timedelta Columns
For duration data stored as timedelta, the .dt.total_seconds() method provides a direct conversion:
import pandas as pd
df = pd.DataFrame({
'duration': pd.to_timedelta(['1:30:45', '2:15:00', '0:45:30'])
})
df['seconds'] = df['duration'].dt.total_seconds()
print(df)
Output:
duration seconds
0 0 days 01:30:45 5445.0
1 0 days 02:15:00 8100.0
2 0 days 00:45:30 2730.0
The total_seconds() method is available only on timedelta columns, not on datetime columns. For datetime columns, calculate total seconds from midnight using the component-based formula shown above.
Available Time Component Attributes
| Attribute | Description | Range |
|---|---|---|
.dt.hour | Hour in 24-hour format | 0 to 23 |
.dt.minute | Minute | 0 to 59 |
.dt.second | Second | 0 to 59 |
.dt.microsecond | Microsecond | 0 to 999999 |
.dt.time | Time as Python time object | N/A |
Practical Examples
Grouping Sales by Hour
Extracting the hour component lets you aggregate data by time of day to identify peak periods:
import pandas as pd
df = pd.DataFrame({
'timestamp': pd.to_datetime([
'2024-01-15 09:30:00', '2024-01-15 09:45:00',
'2024-01-15 10:15:00', '2024-01-15 10:30:00'
]),
'sales': [100, 150, 200, 175]
})
hourly = df.groupby(df['timestamp'].dt.hour)['sales'].sum()
print(hourly)
Output:
timestamp
9 250
10 375
Name: sales, dtype: int64
The 10 AM hour generated more sales (375) than the 9 AM hour (250).
Filtering by Time of Day
Use the extracted hour to filter records to specific time windows:
import pandas as pd
df = pd.DataFrame({
'timestamp': pd.to_datetime([
'2024-01-15 08:30:00', '2024-01-15 12:15:00',
'2024-01-15 18:45:00', '2024-01-15 22:00:00'
]),
'event': ['Login', 'Meeting', 'Logout', 'Alert']
})
# Morning events (before noon)
morning = df[df['timestamp'].dt.hour < 12]
print("Morning events:")
print(morning[['event', 'timestamp']])
print()
# Business hours (9 AM to 5 PM)
business = df[df['timestamp'].dt.hour.between(9, 17)]
print("Business hours events:")
print(business[['event', 'timestamp']])
Output:
Morning events:
event timestamp
0 Login 2024-01-15 08:30:00
Business hours events:
event timestamp
1 Meeting 2024-01-15 12:15:00
Creating a Time-of-Day Category
import pandas as pd
import numpy as np
df = pd.DataFrame({
'timestamp': pd.to_datetime([
'2024-01-15 06:00:00', '2024-01-15 10:00:00',
'2024-01-15 15:00:00', '2024-01-15 21:00:00'
]),
'activity': ['Jog', 'Work', 'Meeting', 'Dinner']
})
hour = df['timestamp'].dt.hour
df['period'] = np.select(
[hour < 12, hour < 17, hour >= 17],
['Morning', 'Afternoon', 'Evening'],
default='Unknown' # <- string default
)
print(df[['activity', 'period']])
Output:
activity period
0 Jog Morning
1 Work Morning
2 Meeting Afternoon
3 Dinner Evening
The .dt accessor works only on columns with datetime64 or timedelta64 dtypes. If your column is stored as strings, convert it first with pd.to_datetime() before accessing .dt attributes.
Quick Reference
| Goal | Method |
|---|---|
| Extract hour | df['col'].dt.hour |
| Extract minute | df['col'].dt.minute |
| Extract second | df['col'].dt.second |
| Total seconds (timedelta) | df['col'].dt.total_seconds() |
| Time component only | df['col'].dt.time |
| Group by hour | df.groupby(df['col'].dt.hour) |
| Filter by time range | df[df['col'].dt.hour.between(9, 17)] |
- Use the
.dtaccessor for fast, vectorized extraction of time components from datetime columns. - Attributes like
.dt.hour,.dt.minute, and.dt.secondreturn integer Series that are immediately useful for grouping, filtering, and feature engineering. - For duration data, use
.dt.total_seconds()on timedelta columns to get a single numeric representation.