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:
datetime | amount | |
---|---|---|
0 | 2023-06-01 18:30:00-04:00 | 155 |
1 | 2023-06-02 18:30:00-04:00 | 110 |
2 | 2023-06-03 18:30:00-04:00 | 99 |
3 | 2023-06-04 18:30:00-04:00 | 77 |
4 | 2023-06-05 18:30:00-04:00 | 134 |
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:
datetime | amount | time | |
---|---|---|---|
0 | 2023-06-01 18:30:00 | 155 | 18:30:00 |
1 | 2023-06-02 18:30:00 | 110 | 18:30:00 |
2 | 2023-06-03 18:30:00 | 99 | 18:30:00 |
3 | 2023-06-04 18:30:00 | 77 | 18:30:00 |
4 | 2023-06-05 18:30:00 | 134 | 18: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:
datetime | amount | time | hours | minutes | seconds | |
---|---|---|---|---|---|---|
0 | 2023-06-01 18:30:00-04:00 | 155 | 18:30:00 | 18 | 30 | 0 |
1 | 2023-06-02 18:30:00-04:00 | 110 | 18:30:00 | 18 | 30 | 0 |
2 | 2023-06-03 18:30:00-04:00 | 99 | 18:30:00 | 18 | 30 | 0 |
3 | 2023-06-04 18:30:00-04:00 | 77 | 18:30:00 | 18 | 30 | 0 |
4 | 2023-06-05 18:30:00-04:00 | 134 | 18:30:00 | 18 | 30 | 0 |
FAQ
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 dt.date as shown below:
sales['date']= sales['datetime'].dt.date
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')