简体   繁体   English

如何使用 pandas 以小时为单位转换 09:20:05 时间格式?

[英]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_timedeltatotal_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.

相关问题 如何在 Pandas 数据框中转换时间 2020-09-25T00:20:00.000Z - How to convert the time 2020-09-25T00:20:00.000Z in pandas dataframe 如何在熊猫中将'1:30:20'字符串转换为时间格式 - How to convert a '1:30:20' string to time format in pandas 如何在 python 中将 (2018-09-05T09:00:06.540486Z) 转换为 (2018-09-05)? - How To Convert (2018-09-05T09:00:06.540486Z) Into (2018-09-05) In python? 解析器错误:小时必须在 0..23:09/05/2019 24:00 - ParserError: hour must be in 0..23: 09/05/2019 24:00 UTC 日期时间问题 - 如何适合冒号 - 时间数据“2021-03-11 09:30:01-05:00”与格式“%Y%m%d %H:%M:%S %z”不匹配' - Problems with UTC datetime - how to fit a colon - time data '2021-03-11 09:30:01-05:00' does not match format '%Y%m%d %H:%M:%S %z' 如何使用python strptime和strftime将2017-02-09T09:43:04.216 + 1000等日期时间格式转换为2017年2月9日? - How to convert a datetime format like 2017-02-09T09:43:04.216+1000 to 09-Feb-2017 using python strptime and strftime? 将熊猫中的对象格式'2014-09-15T11:10:3​​4Z'转换为字符串或日期时间对象 - convert object format '2014-09-15T11:10:34Z' in pandas to string or Date-time object 如何在python中转换不寻常的24小时日期时间格式? - How to convert unusual 24 hour date time format in python? Pandas 转换时间格式 - Pandas convert time format 如何使用 Pandas 在 Wed Oct 02 09:37:43 BST 2019 中读取日期时间格式? - How to read in Wed Oct 02 09:37:43 BST 2019 to datetime format using pandas?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM