In this article we will see how to extract time only from string or datetime in Pandas.
First, we'll create an example DataFrame to test it. Next, we'll explain several examples in more detail.
(1) extract time with .dt.time - datetime.time
df['date'].dt.time
(2) get time by .dt.strftime('%H:%M') as string
df['date'].dt.strftime('%H:%M')
Setup
Let's work with the following DataFrame which has date and time information stored as a string:
import pandas as pd
dict = {'date': {0: '28-01-2022 5:25:00 PM',
1: '27-02-2022 6:25:00 PM',
2: '30-03-2022 7:25:00 PM',
3: '29-04-2022 8:25:00 PM',
4: '31-05-2022 9:25:00 PM'},
'date_short': {0: 'Jan-2022', 1: 'Feb-2022', 2: 'Mar-2022', 3: 'Apr-2022', 4: 'May-2022'}}
df = pd.DataFrame(dict)
DataFrame looks like:
date | date_short | |
---|---|---|
0 | 28-01-2022 5:25:00 PM | Jan-2022 |
1 | 27-02-2022 6:25:00 PM | Feb-2022 |
2 | 30-03-2022 7:25:00 PM | Mar-2022 |
3 | 29-04-2022 8:25:00 PM | Apr-2022 |
4 | 31-05-2022 9:25:00 PM | May-2022 |
String to datetime
Convert string to datetime with Pandas:
df['date'] = pd.to_datetime(df['date'])
Extract time with .dt.time as datetime.time
Once we have datetime in Pandas we can extract time very easily by using: .dt.time
.
Default format of extraction is: HH:MM:SS
. It returns a numpy array of datetime.time objects.
df['date'].dt.time
will give us:
0 17:25:00
1 18:25:00
2 19:25:00
3 20:25:00
4 21:25:00
Name: date, dtype: object
Get time by .dt.strftime('%H:%M') as string
For custom format we can use - .dt.strftime('%H:%M')
.
strftime
returns strings formatted in time format given as parameter
df['date'].dt.strftime('%H:%M')
will give us:
0 17:25
1 18:25
2 19:25
3 20:25
4 21:25
Name: date, dtype: object
We can find more information on this link: pandas.Series.dt.strftime
Conclusion
To summarize we saw how to extract time with Pandas in two ways. First by using .dt.time
as datetime.
Second one extracts time as a string in any format needed.