Date time difference in minutes python

Question:

I’m new to python and tiring to calculate time difference in minutes. Times are in slightly two different formats. I have tried below to format but did not got it correctly

from datetime import datetime
start = "2023-05-21T11:40:54.532203+00:00"
end = "2023-05-21T11:45:00+00:00"

starttime=datetime.strptime(start , "%Y-%m-%dT%H:%M:%S:%f%z'")
endtime=datetime.strptime(end , "%Y-%m-%dT%H:%M:%S:%f%z'")
Asked By: user12073359

||

Answers:

from datetime import datetime

start = "2023-05-21T11:40:54.532203+00:00"
end = "2023-05-21T11:45:00+00:00"


def time_diff(start,end):
    start = datetime.strptime(start,"%Y-%m-%dT%H:%M:%S.%f%z")
    end = datetime.strptime(end,"%Y-%m-%dT%H:%M:%S%z")
    ##return in minutes
    return (end - start).total_seconds() / 60

print(time_diff(start,end))
Answered By: Utku Can

Try this:

from datetime import datetime

start = "2023-05-21T11:40:54.532203+00:00"
end = "2023-05-21T11:45:00+00:00"

starttime = datetime.strptime(start, "%Y-%m-%dT%H:%M:%S.%f%z")
endtime = datetime.strptime(end, "%Y-%m-%dT%H:%M:%S%z")

Now, to find the time difference in minutes, you can subtract starttime from endtime and use the total_seconds() function to get the difference in seconds. Then, you can divide by 60 to convert it to minutes:

time_difference = endtime - starttime
minutes_difference = time_difference.total_seconds() / 60
print(minutes_difference)

I got 4.09112995.

Answered By: cconsta1