Home > Mobile >  Python/Pandas Calculate the mean time (hour) of a Datetime column
Python/Pandas Calculate the mean time (hour) of a Datetime column

Time:04-29

I have a Pandas DataFrame (data) with a column ['Date'] in DateTime (date and time) which represents the time of arrival.

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

And then calculate data['Time'].mean() but it shows: " 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

Thanks for your help!

CodePudding user response:

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

CodePudding user response:

Try this

datetimelist = data['Date'].tolist()
avg=pd.to_datetime(pd.Series(datetimelist)).mean()
  • Related