how to calculate time between two datetime in python?

Question:

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'
Asked By: mikezang

||

Answers:

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
Answered By: artemis
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.