problem with division, divided by datetime and int

33 Views Asked by At

I have dataFrame, two columns:

  • first is result['days'] int type,
  • second is result['time'], datetime.time type. It's sum of time like 02:27:39

What I want is new column = result['time'] / result['days'] but I can't

unsupported operand type(s) for /: 'datetime.time' and 'int'

How can I do this?

1

There are 1 best solutions below

0
Mark Tolonen On BEST ANSWER

A datetime.time cannot be divided, but a datetime.timedelta can:

import pandas as pd
import datetime as dt

def to_timedelta(time):
    return dt.timedelta(hours=time.hour, minutes=time.minute, seconds=time.second)

df = pd.DataFrame({'days':[1,2,3], 'time':[dt.time(2,27,39)]*3})
df['per_day'] = df.time.apply(to_timedelta) / df.days
print(df)

Output:

   days      time                per_day
0     1  02:27:39        0 days 02:27:39
1     2  02:27:39 0 days 01:13:49.500000
2     3  02:27:39        0 days 00:49:13