dataframedatetimedivide

problem with division, divided by datetime and int


I have dataFrame, two columns:

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?


Solution

  • 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