[英]How to convert 09:20:05 time format in hour using pandas?
I have a df where a column contains time value and i want to convert it into hour and also compare it with 0.我有一个 df,其中一列包含时间值,我想将其转换为小时并将其与 0 进行比较。
For Ex: Time = [02:20:10,01:10:05,03:20:14,04:34:09,05:05:34,06:40:20] And Want:例如:时间 = [02:20:10,01:10:05,03:20:14,04:34:09,05:05:34,06:40:20] 并且想要:
Time = [02,01,03,04,05,06] in int format....时间 = [02,01,03,04,05,06] int 格式....
You can use to_timedelta
and total_seconds
, then perform integer division by 3600 seconds with floordiv
您可以使用to_timedelta
和total_seconds
,然后使用floordiv
执行 integer 除以 3600 秒
If you have a column/Series:如果您有专栏/系列:
pd.to_timedelta(df['Time']).dt.total_seconds().floordiv(3600).astype(int)
output: output:
0 2
1 1
2 3
3 4
4 5
5 6
Name: Time, dtype: int64
From a python list:从 python 列表中:
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')
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 (eg, '34:12:56'
).此解决方案适用于任意小时数(例如'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
.如果你确定你的时间不能超过'23:59:59',你也可以使用pd.to_datetime(df['Time']).dt.hour
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.