Extract Hours from DateTime Pandas Series

Viewed 777

I have a Pandas Series of DateTime

>> s
0             NaT
3        23:00:42
26            NaT
53       23:58:58
89       01:06:27
           ...   
20215         NaT
20217         NaT
20239    23:28:38
20246         NaT
20270         NaT

I first drop the NaT using:

s.dropna()
3        23:00:42
53       23:58:58
89       01:06:27
97       01:18:36
195      05:43:07
           ...   
20132    19:21:20
20141    20:08:01
20152    20:21:01
20199    22:25:50
20239    23:28:38

Now I try to get the hours from the series but not sure how to do that.

3 Answers

Use if s is Series convert values to datetimes and then extract hours:

s = pd.to_datetime(s.astype(str)).dt.hour

Or get first 2 values and convert to floats:

s = s.str[:2].astype(float)

If working with column:

df['hour'] = pd.to_datetime(df['col'].astype(str)).dt.hour

Or:

df['hour'] = df['col'].str[:2].astype(float)

Try this:

s['hour'] = s['time'].apply(lambda x: x[3:5])

There are many approaches. I would do it like this:

s = pd.Series(pd.to_datetime(x).hour for x in s) 
Related