Skip to content Skip to sidebar Skip to footer

Pandas - How To Extract HH:MM From Datetime Column In Python?

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

Solution 1:

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

Solution 2:

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

Solution 3:

General solution (not pandas based)

import time
top = '2018-07-25 11:14:00'
time_struct = time.strptime(top, '%Y-%m-%d %H:%M:%S')
short_top = time.strftime('%H:%M', time_struct)
print(short_top)

Output

11:14

Post a Comment for "Pandas - How To Extract HH:MM From Datetime Column In Python?"