Search code examples
pythondatetimetimedelta

how to calculate time between two datetime in python?


I have two datetime as below

start=2023/04/05 08:00:00, end=2023/04/05 16:00:00

I want to get time by

lTime = start + (end - start) /3 or 
lTime = (start * 2 + end) /3 

I used code as below

lTime = start + timedelta(end - start) / 3

but I got error, what can I do?

unsupported operand type(s) for -: 'builtin_function_or_method' and 'datetime.datetime'

Solution

  • You need to be using datetime objects to do this calculation.

    from datetime import datetime, timedelta
    
    start_str = '2023/04/05 08:00:00'
    end_str = '2023/04/05 16:00:00'
    
    start = datetime.strptime(start_str, '%Y/%m/%d %H:%M:%S')
    end = datetime.strptime(end_str, '%Y/%m/%d %H:%M:%S')
    
    lTime = start + (end - start) / 3