Calculating Time in Python (datetime.timedelta?)
I am sure this is a nobrainer for a lot of you, but I find myself really confused with the whole datetime.timedelta thing. Essentially I timestamp something when I start startTime
and then I timestamp the end of the process endTime
and I am trying to get the difference in HH:MM:SS and am having no luck.
I get this error when I do print endTime - startTime
:
TypeError: unsupported operand type(s) for -: 'datetime.time' and 'datetime.time'
Edited to include final result:
startTime = datetime.now()
<... my looping process ...>
endTime = datetime.now()
calcdTime = endTime - startTime
print str(calcdTime)[:-4]
Thi开发者_如何学运维s outputs to: H:MM:SS.MM (thus stripping the last 4 characters off the timedelta
Use a datetime
instead of a time
. Subtracting one time from another is meaningless without a date; you can't just assume that they're on the same day and the left operand comes first.
Depending on what you're doing with the information, you might want to just use time.time
:
import time
starttime = time.time()
# do stuff
endtime = time.time()
elapsed = endtime - starttime
print elapsed
Which will give you the elapsed time in seconds. This is often more convenient than having a timedelta
.
精彩评论