How to extract the time only from pandas datetime objects?

Step 1: Create your datetime Series

We will start by importing the pandas library into your Python development environment. Next, we will define a simple example DataFrame consisting of sales figures for some random date ranges.

import pandas as pd

dates = pd.date_range(start='6/1/23 18:30:00', periods = 5, tz = 'America/Detroit')
amount = [155, 110, 99, 77, 134]
sales = pd.DataFrame(dict(datetime=dates, amount = amount))
sales.head()

Here’s our data:

datetimeamount
02023-06-01 18:30:00-04:00155
12023-06-02 18:30:00-04:00110
22023-06-03 18:30:00-04:0099
32023-06-04 18:30:00-04:0077
42023-06-05 18:30:00-04:00134

Note: you can use the dt.timez_convert() function to change the time zone of your date values as needed.

Step 2: Get the time values from you Date column

To get only the time value (in hh:mm:sss format) s from a Series of date time objects into a newly created column, use the following Python code:

sales['time']= sales['datetime'].dt.time

This will create the time column as shown below:

datetimeamounttime
02023-06-01 18:30:0015518:30:00
12023-06-02 18:30:0011018:30:00
22023-06-03 18:30:009918:30:00
32023-06-04 18:30:007718:30:00
42023-06-05 18:30:0013418:30:00

Step 3: Extract hour, minutes, seconds from datetime

We can use the dt accessor to get not only the time and time zone; but also other elements such as hour, minutes, seconds values etc’. Here are a few examples you can use:

sales['hours']= sales['datetime'].dt.hour

sales['minutes']= sales['datetime'].dt.minute

sales['seconds']= sales['datetime'].dt.second

After running the snippet above, you will get the following DataFrame:

datetimeamounttimehoursminutesseconds
02023-06-01 18:30:00-04:0015518:30:0018300
12023-06-02 18:30:00-04:0011018:30:0018300
22023-06-03 18:30:00-04:009918:30:0018300
32023-06-04 18:30:00-04:007718:30:0018300
42023-06-05 18:30:00-04:0013418:30:0018300

Related Learning

How to group pandas data by time values?