scopa
scopa

Reputation: 523

Python3 Calculating Time using datetime?

I want to enter a start and end time: date & time I want to run calculations on the elapsed time between the two dates.

trying to understand datetime, date, time, timedelta. strptime/strftime

If user enters; start_time: 2017,7,15 10:45 am end_time: 2017,7,16 1:30 am

calc the hours/mins using diff weights: 10:45am -> 9:00pm = 10:15*2 9:00pm -> 1:30am = 4:30*2.5

Tried something like this:

st_date = date(2017, 6, 15)
st_time = time(10, 45)
start = datetime.combine(st_date, st_time)

end_date = date(2017, 6, 15)
end_time = time(22, 30)
end = datetime.combine(end_date, end_time)

st = datetime.strftime(end, '%Y %B %d %I:%M %p')
et = datetime.strftime(start, '%Y %B %d %I:%M %p')

But it is completely wrong. I can't perform an operation on the strftime object. Can you please point me in the right direction on how to proceed.

Upvotes: 1

Views: 889

Answers (1)

Joshua Wade
Joshua Wade

Reputation: 5293

I can't perform an operation on the strftime object.

The strftime function returns a nicely formatted string, not a datetime object. If you were to print(st), you would get 2017 June 15 10:45 AM.

If you want to get the time elapsed between two datetime objects, just subtract them, like so:

from datetime import date
from datetime import time
from datetime import datetime

st_date = date(2017, 6, 15)
st_time = time(10, 45)
start = datetime.combine(st_date, st_time)

end_date = date(2017, 6, 15)
end_time = time(22, 30)
end = datetime.combine(end_date, end_time)

diff = end - start

This produces a timedelta object. Now, if you want the elapsed time in seconds, you can just do this:

elapsed_time = diff.total_seconds()

Upvotes: 1

Related Questions