How to convert 09:20:05 time format in hour using pandas?

Viewed 30

I have a df where a column contains time value and i want to convert it into hour and also compare it with 0.

For Ex: Time = [02:20:10,01:10:05,03:20:14,04:34:09,05:05:34,06:40:20] And Want:

Time = [02,01,03,04,05,06] in int format....

1 Answers

You can use to_timedelta and total_seconds, then perform integer division by 3600 seconds with floordiv

If you have a column/Series:

pd.to_timedelta(df['Time']).dt.total_seconds().floordiv(3600).astype(int)

output:

0    2
1    1
2    3
3    4
4    5
5    6
Name: Time, dtype: int64

From a python list:

Time = ['02:20:10','01:10:05','03:20:14','04:34:09','05:05:34','06:40:20']

pd.to_timedelta(Time).total_seconds()//3600

output: Float64Index([2.0, 1.0, 3.0, 4.0, 5.0, 6.0], dtype='float64')

NB. This solution works for any number of hours (e.g., '34:12:56'). If you are sure that your time cannot exceed '23:59:59', you could also use pd.to_datetime(df['Time']).dt.hour.

Related