简体   繁体   English

Python/Pandas 计算 Datetime 列的平均时间(小时)

[英]Python/Pandas Calculate the mean time (hour) of a Datetime column

I have a Pandas DataFrame (data) with a column ['Date'] in DateTime (date and time) which represents the time of arrival.我有一个 Pandas DataFrame(数据),在 DateTime(日期和时间)中有一列['Date'] ,代表到达时间。

How to calculate the mean of only the time of the day, (not date) and get a time in Hours, Minutes, Seconds?如何仅计算一天中的时间(不是日期)的平均值,并以小时、分钟、秒为单位计算时间?

I tried: data['Time'] = data['Date'].dt.time我试过: data['Time'] = data['Date'].dt.time

And then calculate data['Time'].mean() but it shows: " TypeError: unsupported operand type(s) for +: 'datetime.time' and 'datetime.time' "然后计算data['Time'].mean()但它显示:“ TypeError: unsupported operand type(s) for +: 'datetime.time' and 'datetime.time'

The sample of my data:我的数据样本:

    Date
35  2021-12-02 09:03:00
36  2021-12-01 08:57:00
37  2021-11-30 08:50:00
38  2021-11-29 08:40:00
39  2021-11-28 10:31:00
41  2021-11-25 08:58:00
43  2021-11-23 08:37:00
44  2021-11-22 08:56:00
45  2021-11-19 09:00:00
46  2021-11-18 09:30:00
47  2021-11-17 08:47:00
48  2021-11-16 08:45:00
49  2021-11-15 09:44:00

Use:利用:

data['Time'] = pd.to_timedelta(data['Date'].dt.time.astype(str))

import datetime
out = data['Time'].mean()
print (out)
0 days 09:06:00

time = (datetime.datetime.min + out).time()
print (time)
09:06:00

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM