lasan13
lasan13

Reputation: 33

How to extract hours from time stamp column in pandas data frame and convert to float type

Hi I want to create a liner regression prediction model and want to get a time as a independent variable. My data frame has a time stamp and I wanted to extract the hours from it and put in to separate column as float data type. Highly appreciate your support on this . Thank you. Time stamp 12/1/2021 8:39 7/10/2020 13:47 1/11/2020 11:53 4/10/2020 12:33 11/10/2020 12:40

Upvotes: 0

Views: 390

Answers (1)

jezrael
jezrael

Reputation: 862791

Use to_datetime with hour:

#DD/MM/YYYY H:M
pd.to_datetime(df['Time stamp'], format='%d/%m/%Y %H:%M').dt.hour.astype(float)

#MM/DD/YYYY H:M
pd.to_datetime(df['Time stamp'], format='%m/%d/%Y %H:%M').dt.hour.astype(float)

Or extract digits between space and ::

df['Time stamp'].str.extract('\s+(\d+):').astype(float)

Upvotes: 3

Related Questions