Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas - How to extract HH:MM from datetime column in Python?

Tags:

python

pandas

I just want to extract from my df HH:MM. How do I do it?

Here's a description of the column in the df:

count                     810
unique                    691
top       2018-07-25 11:14:00
freq                        5
Name: datetime, dtype: object

The string value includes a full time stamp. The goal is to parse each row's HH:MM into another df, and to loop back over and extract just the %Y-%m-%d into another df.

like image 970
uncle-junky Avatar asked Feb 17 '19 12:02

uncle-junky


2 Answers

Assume the df looks like

print(df)

             date_col
0 2018-07-25 11:14:00
1 2018-08-26 11:15:00
2 2018-07-29 11:17:00
#convert from string to datetime
df['date_col'] = pd.to_datetime(df['date_col']) 

#to get date only
print(df['date_col'].dt.date)
0    2018-07-25
1    2018-08-26
2    2018-07-29

#to get time:
print(df['date_col'].dt.time)

0    11:14:00
1    11:15:00
2    11:17:00
#to get hour and minute
print(df['date_col'].dt.strftime('%H:%M'))
0    11:14
1    11:15
2    11:17
like image 96
anky Avatar answered Sep 28 '22 04:09

anky


First convert to datetime:

df['datetime'] = pd.to_datetime(df['datetime'])

Then you can do:

df2['datetime'] = df['datetime'].dt.strptime('%H:%M')
df3['datetime'] = df['datetime'].dt.strptime('%Y-%m-%d')
like image 36
WhiteHat Avatar answered Sep 28 '22 02:09

WhiteHat