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))

Here’s our data:

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:

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:

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


How can i get just the date values from a datetime object in pandas?

Yes, you can retrieve only the date value, by using the as shown below:

sales['date']= sales['datetime']

How to separate rows into morning and afternoon using pandas?

You can use the following lambda function:

sales['AM-PM'] = sales['datetime_col'].dt.hour.apply(lambda x: 'AM' if x < 12 else 'PM')

How to round the time to the nearest hour in pandas?

You can round the time values using the dt.round() function:

sales['round_hour'] = sales['datetime_col'].dt.round('H')

Related Learning

How to group pandas data by time values?